LeetCode-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.

Hints:

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

需要注意先保存好左右儿子指针

class Solution {
public:
    void sub(TreeNode* root,TreeNode** pre){
        TreeNode* left=root->left;
        TreeNode* right=root->right;
        if((*pre)!=NULL){
            (*pre)->right=root;
            (*pre)->left=NULL;
        }
        *pre=root;
        if(left!=NULL)
        sub(left,pre);
        if(right!=NULL)
        sub(right,pre);
    }
    void flatten(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(root==NULL)return;
        TreeNode* pre=NULL;
        sub(root,&pre);
    }
};
View Code

 

posted @ 2013-10-04 16:36  懒猫欣  阅读(142)  评论(0编辑  收藏  举报