您的位置:首页 > 其它

leetcode Flatten Binary Tree to Linked List

2013-10-15 15:26 267 查看
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


I finished this problem in a direct way. However, the result was Runtime Error because I didn't set the left child to null when I submitted the first time.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private :
  vector<TreeNode *> temp ;// record the preOrder result 
public:
   void preOrder(TreeNode *root){
    temp.push_back(root);
    if(root->left) preOrder(root->left);
    if(root->right) preOrder(root->right);
   
   }
    void flatten(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        temp.clear();
        if(root == NULL) return ;
        preOrder(root);
        for(int i = 0; i< temp.size()-1; i++)
         {
            temp[i]->right = temp[i+1];
            temp[i]->left = NULL ;//essential
         }
       
    }
};


There is another way to solve this problem. Initially, root-->left, root-->right,
if(root->left==null)

nothing needs to do.

if(root->left!=null){

find the rightest node of root->left

rightest node->next=root->right;

root->right=root->left; //because of the pre-order

}

The following is the code :

/**
 * 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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        TreeNode *p;
        if(root==NULL)  return;
        flatten(root->left);
        flatten(root->right);
        if(root->left==NULL)    return;
        p=root->left;
        while(p->right!=NULL)   p=p->right;
        p->right=root->right;
        root->right=root->left;
        root->left=NULL;
        
		return;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: