直接通过中序遍历来解。但是需要设置两个节点记录每个子树排序后的第一和最后一个节点,尤其是最后一个,因为最后一个节点是由于连接所需。
上代码:
class Solution {public: TreeNode* Convert(TreeNode* pRootOfTree) { TreeNode* head=NULL;//每个子树排序后的第一个节点 TreeNode* tail=NULL;//每个子树排序后的最后一个节点 ConvertHelp(pRootOfTree,head,tail); return head; } void ConvertHelp(TreeNode* pRootOfTree,TreeNode* &head,TreeNode* &tail) { if(pRootOfTree==NULL) return; ConvertHelp(pRootOfTree->left,head,tail); if (tail == NULL) { //说明找到了中序遍历的第一个节点,把其作为链表头节点 tail = pRootOfTree; head = pRootOfTree; } else { tail->right = pRootOfTree; pRootOfTree->left = tail; tail = pRootOfTree; } ConvertHelp(pRootOfTree->right,head,tail); }};
法二:(思路同上,但是更简洁)
class Solution {public: TreeNode* Convert(TreeNode* pRootOfTree) { if(pRootOfTree == nullptr) return nullptr; TreeNode* pre = nullptr; convertHelper(pRootOfTree, pre); TreeNode* res = pRootOfTree; while(res ->left) res = res ->left; return res; } void convertHelper(TreeNode* cur, TreeNode*& pre) { if(cur == nullptr) return; convertHelper(cur ->left, pre); cur ->left = pre; if(pre) pre ->right = cur; pre = cur; convertHelper(cur ->right, pre); }};