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

【Flatten Binary Tree to Linked List】cpp

时间:2015-05-15 10:23:04      阅读:119      评论: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

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
            if (!root) return;
            stack<TreeNode *> sta;
            TreeNode *dummy = new TreeNode(INT_MIN);
            TreeNode *pre = dummy;
            dummy->right = root;
            sta.push(root);
            while ( !sta.empty() )
            {
                TreeNode *tmp = sta.top(); sta.pop();
                if ( tmp->right ) sta.push(tmp->right);
                if ( tmp->left ) sta.push(tmp->left);
                tmp->left = NULL;
                pre->right = tmp;
                pre = tmp;
            }
    }
};

tips:

先序遍历(node->left->right);每次出栈的元素都切断left(为什么right不用切?因为在下一次迭代的时候,pre->right自然就把right的值覆盖了)。

设立一个pre节点,保存上一次出栈的元素。

pre->right = tmp就能按照题意把原有的tree给flatten了。

===================================

学习了一个递归版的代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        // terminal condition
        if (!root) return;
        // recersive left and child
        flatten(root->left);
        flatten(root->right);
        // if left is not null then do the reconnection
        if (!root->left) return;
        TreeNode *p = root->left;
        while ( p->right) p = p->right;
        p->right = root->right;
        root->right = root->left;
        root->left = NULL;
    }
};

 

【Flatten Binary Tree to Linked List】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4505174.html

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