LeetCode 114.Flatten Binary Tree to Linked List (二叉树展开为链表)

题目描述:

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

例如,给定二叉树

    1
   / \
  2   5
 / \   \
3   4   6

将其展开为:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

AC C++ Solution:
 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        TreeNode* now = root;
        while(now) {
            if(now->left)
            {
                TreeNode *pre = now->left;
                while(pre->right) {
                    pre = pre->right;
                }
                pre->right = now->right;        //将当前节点的右子树转接到左子节点的右叶节点上
                now->right = now->left;         //将当前节点的右子树用左子树代替
                now->left = NULL;
            }
            now = now->right;                   //遍历下一个节点
        }
    }
};

类似的:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        while(root) {
            if(root->left && root->right) {
                TreeNode* t = root->left;
                while(t->right)
                    t = t->right;
                t->right = root->right;    //将当前节点的右子树接到左子树的右叶节点上
            }
            
            if(root->left)
                root->right = root->left;  //再将当前节点的右子树替换为左子树
            root->left = NULL;
            root = root->right;      
        }
    }
};

猜你喜欢

转载自blog.csdn.net/amoscykl/article/details/82964158