114. 二叉树展开为链表

给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
 

    1
   / \
  2   5
 / \   \
3   4   6

将其展开为:
 

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

递归解法:

很明显,对于根节点root,分别保存其左右孩子的节点,然后root指向的左孩子设置为空,左孩子的节点所展开成的链表连在root的右孩子节点上,再将右孩子的节点展开成的链表连接在root链表的最末端。

class Solution {
public:
    void flatten(TreeNode* root) {
        if(root==nullptr)return;
        flatten(root->left);
        flatten(root->right);
        TreeNode *temp=root->right;
        root->right=root->left;
        root->left=NULL;
        while(root->right)
            root=root->right;
        root->right=temp;
    }
};

非递归解法:

这个方法是从根节点开始出发,先检测其左子结点是否存在,如存在则将根节点和其右子节点断开,将左子结点及其后面所有结构一起连到原右子节点的位置,把原右子节点连到原左子结点最后面的右子节点之后。然后再判断链表的下一个节点。

class Solution {
public:
    void flatten(TreeNode* root) {
        if(root==NULL) return;
        TreeNode* cur = root;
        while(cur){
            if(cur->left){
                //找到左子树最右下角的节点p
                TreeNode* next = cur->left;
                while(next->right)
                    next = next->right;
                //把cur的右子树设为p的右子树
                next->right = cur->right;
                //把cur的左子树变为右子树
                cur->right = cur->left;
                cur->left = NULL;
                
            }
            cur = cur->right;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/hlk09/article/details/82119708