LeetCode OJ - Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1
        / \
       2   5
      / \   \
     3   4   6

The flattened tree should look like:
   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6

click to show hints.

分析:root -> left -> right 其中root->right一定是指向原来的左子树,而原来的左子树最后一个元素指向原来的右子树,第一次得到下面的结果


接着以2为root节点,继续调整下面的树,整个过程可以形成递归,当然也可以用迭代来做

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode *root) {
        if(root == NULL) return ;
        while(root) {
            if(root->left) {
                TreeNode *p = root->left;
                //寻找左子树“最后”一个节点
                while(p->right) p = p->right;
                //根、左子树、右子树的连接
                p->right = root->right;
                root->right = root->left;
                root->left = NULL;
            }
            
            root = root->right;
        }
    } 
};

下面是递归代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode *root) {
        if(root == NULL) return ;
        Adjust(root);
    } 
    
    void Adjust(TreeNode * root) {
        if(root == NULL) return ;
        
        if(root->left) {
            TreeNode *p = root->left;
            //寻找左子树“最后”一个节点
            while(p->right) p = p->right;
            //根、左子树、右子树的连接
            p->right = root->right;
            root->right = root->left;
            root->left = NULL;
        }
        
        Adjust(root->right);
    }
};








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章