[LeetCode-114] Flatten Binary Tree to Linked List

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

 

 

前序历遍的变形吧。

 

 1 /**
 2  * Definition for binary tree
 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 public:
12     void flatten(TreeNode *root) {
13         // Start typing your C/C++ solution below
14         // DO NOT write int main() function
15         if (NULL == root) {
16             return;
17         }
18         bool is_flatten = false;
19         TreeNode *pnext = NULL, *pnode = NULL, *pright = NULL;
20         while (!is_flatten) {
21             pnode = pnext = root;
22             is_flatten = true;
23             while (NULL != pnext->left || NULL != pnext->right) {
24                 if (NULL != pnext->left) {
25                     is_flatten = false;
26                     pnode = pnext;
27                     pnext = pnext->left;
28                 } else {
29                     pnext = pnext->right;
30                 }
31             }
32             if (!is_flatten) {
33                 pright = pnode->right;
34                 pnode->right = pnode->left;
35                 pnode->left = NULL;
36                 while (NULL != pnode->right) {
37                     pnode = pnode->right;
38                 }
39                 pnode->right = pright;
40             }
41         }  
42     }  
43 };  
View Code

 

 

posted on 2013-09-11 22:13  似溦若岚  阅读(136)  评论(0编辑  收藏  举报

导航