114. Flatten Binary Tree to Linked List

Total Accepted: 84864 Total Submissions: 270352 Difficulty: Medium

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.

Hints:

If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.


分析:

申請空間來記錄前序遍歷的結果,然後根據對應關係,建立鏈接,即碾平。

/**
 * 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 dfs(vector<TreeNode*> &result,TreeNode* root)
    {
        if(root!=NULL){  
            result.push_back(root);  
            dfs(result,root->left);  
            dfs(result,root->right);  
        }  
    }
    void flatten(TreeNode* root) {
        if(root==NULL)
            return;
        vector<TreeNode*> result;//存在空間複雜度
        dfs(result,root);//前序遍歷
        //碾平過程
        for(int i=0;i<result.size()-1;i++)
        {
            result[i]->right=result[i+1];//建立連接
            result[i]->left=NULL;
        }
    }
};


別人家的解法,無空間浮渣度:

class Solution {
public:
    void flatten(TreeNode *root) {
        TreeNode*now = root;
        while (now)
        {
            if(now->left)
            {
                //Find current node's prenode that links to current node's right subtree
                TreeNode* pre = now->left;
                while(pre->right)
                    pre = pre->right;
           
                pre->right = now->right;
                //Use current node's left subtree to replace its right subtree(original right 
                //subtree is already linked by current node's prenode
                now->right = now->left;
                now->left = NULL;
            }
            now = now->right;
        }
    }
};



注:本博文爲EbowTang原創,後續可能繼續更新本文。如果轉載,請務必複製本條信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51647971

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode題解索引:http://blog.csdn.net/ebowtang/article/details/50668895

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