码迷,mamicode.com
首页 > 其他好文 > 详细

Flatten Binary Tree to Linked List

时间:2014-08-16 22:23:31      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   ar   div   amp   

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

思路:该题本质上是二叉树的先序遍历。我们首先来看递归的解法,函数FlattenSub(node)对以node为根的树进行处理,同时返回先序序列的尾节点的指针:

 1 class Solution {
 2 public:
 3     void flatten( TreeNode *root ) {
 4         if( !root ) { return; }
 5         FlattenSub( root );
 6     }
 7 private:
 8     TreeNode *FlattenSub( TreeNode *node ) {
 9         if( node->left ) {
10             TreeNode *left_last = FlattenSub( node->left );
11             left_last->right = node->right;
12             node->right = node->left;
13             node->left = 0;
14             return FlattenSub( left_last );
15         }
16         if( node->right ) { return FlattenSub( node->right ); }
17         return node;
18     }
19 };

接下来再看迭代的解法,基本思想是将父节点的地址保存到其左子树最右侧节点(即先序遍历的尾节点)的右指针字段,这样在左子树处理完成之后,可以再次回到父节点以完成对右子树的处理。

 1 class Solution {
 2 public:
 3     void flatten( TreeNode *root ) {
 4         if( !root ) { return; }
 5         while( root ) {
 6             if( root->left ) {
 7                 TreeNode *node = root->left;
 8                 while( node->right && node->right != root ) { node = node->right; }
 9                 if( node->right == root ) {
10                     node->right = root->right;
11                     root->right = root->left;
12                     root->left = 0;
13                 } else {
14                     node->right = root;
15                     root = root->left;
16                 }
17             }
18             TreeNode *node = root;
19             while( node->right && !node->right->left ) { node = node->right; }
20             if( node->right && node->right->left == root ) {
21                 root = node->right;
22                 node->right = root->right;
23                 root->right = root->left;
24                 root->left = 0;
25             } else {
26                 root = node->right;
27             }
28         }
29         return;
30     }
31 };

 

Flatten Binary Tree to Linked List,布布扣,bubuko.com

Flatten Binary Tree to Linked List

标签:style   blog   color   io   for   ar   div   amp   

原文地址:http://www.cnblogs.com/moderate-fish/p/3916219.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!