面试题6:二叉树转单链表

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

 1 class Solution {
 2 public:
 3     void flatten(TreeNode* root) {
 4         if (root == nullptr)
 5             return;
 6         flatten(root->left);
 7         flatten(root->right);
 8         TreeNode* tmp = root->right;
 9         root->right = root->left;
10         root->left = nullptr;
11         TreeNode* p = root;
12         while (p->right)
13             p = p->right;
14         p->right = tmp;
15     }
16 }

 

posted @ 2017-05-13 11:35  wxquare  阅读(420)  评论(0编辑  收藏  举报