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

leetcode 114 . Flatten Binary Tree to Linked List

时间:2015-02-11 18:19:57      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

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 void flatten(TreeNode *root) 
 2     {
 3         vector<TreeNode *> tree_nodes;
 4         stack<TreeNode *> stree;
 5         TreeNode *visit = root;
 6         if (root == NULL)
 7             return;
 8         while (!stree.empty() && visit != NULL)
 9         {
10             if (visit != NULL)
11             {
12                 tree_nodes.push_back(visit);
13                 if (visit->right != NULL)
14                     stree.push(visit);
15                 visit = visit->left;
16             }
17             else
18             {
19                 visit = stree.top();
20                 stree.pop();
21             }
22         }
23         
24         visit = root;
25         visit->left = NULL;
26         for (int i = 1; i < tree_nodes.size(); i++)
27         {
28             visit->right = tree_nodes[i];
29             visit->left = NULL;
30             visit = visit->right;
31         }
32     }

 

leetcode 114 . Flatten Binary Tree to Linked List

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4286619.html

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