首页 > 其他 > 详细

[Leetcode] Flatten Binary Tree to Linked List

时间:2014-04-05 18:32:29      阅读:512      评论: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

前序遍历,注意保存中间变量。

bubuko.com,布布扣
 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 helper(TreeNode *root, TreeNode *&pre) {
13         if (root == NULL) return;
14         if (pre != NULL) {
15             pre->left = NULL;
16             pre->right = root;
17         }
18         pre = root;
19         TreeNode *left = root->left;
20         TreeNode *right = root->right;
21         if (left != NULL) {
22             helper(left, pre);
23         }
24         if (right != NULL) {
25             helper(right, pre);
26         }
27     }
28     void flatten(TreeNode *root) {
29         TreeNode *pre = NULL;
30         helper(root, pre);
31     }
32 };
bubuko.com,布布扣

 

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

[Leetcode] Flatten Binary Tree to Linked List

原文:http://www.cnblogs.com/easonliu/p/3646841.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!