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);
    }
};








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