leetcode-114. 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

思路:递归处理,引用二叉链表的思想,使用pre记录上一个分支的指针。

Accepted Code:
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 private:
12     TreeNode* pre=nullptr;
13 public:
14     void flatten(TreeNode* root) {
15         if(root==nullptr)
16         return;
17         flatten(root->right);
18         flatten(root->left);
19         root->right=pre;
20         root->left=nullptr;
21         pre=root;
22     }
23 };

 

posted @ 2017-02-21 11:48  Pacific-hong  阅读(128)  评论(0编辑  收藏  举报