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

Flatten Binary Tree to Linked List

时间:2014-08-26 17:17:06      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   io   strong   for   ar   

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.

使用先序遍历迭代方式,直接代码如下:

 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         if( !root ) return;
14         stack<TreeNode*> qt;
15         qt.push(root); 
16         TreeNode* pre = 0;  //记录前驱节点
17         while( !qt.empty() ) {
18             TreeNode* cur = qt.top();
19             qt.pop();
20             if( cur->right ) qt.push(cur->right);   //先放右子树
21             if( cur->left ) qt.push(cur->left);     //再放左子树
22             if( pre ) { //如果前驱节点不为空的情况下
23                 pre->right = cur;
24                 pre->left = 0;
25             }
26             pre = cur;  //更新前驱节点
27         }
28         pre->right = 0;
29         pre->left = 0;
30     }
31 };

 

Flatten Binary Tree to Linked List

标签:style   blog   http   color   使用   io   strong   for   ar   

原文地址:http://www.cnblogs.com/bugfly/p/3937485.html

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