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

Leetcode Flatten Binary Tree to Linked List

时间:2014-07-03 20:32:55      阅读:429      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   art   

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,布布扣
class Solution {
public:
    vector<TreeNode *> res;
    
    void preTraverse(TreeNode *root){
        if(root == NULL) return;
        res.push_back(root);
        preTraverse(root->left);
        preTraverse(root->right);
    }
    
    void flatten(TreeNode *root) {
        if(root == NULL) return;
        preTraverse(root);
        for(int i = 1 ; i < res.size(); ++ i){
            res[i-1]->left =NULL;
            res[i-1]->right = res[i];
        }
        res[res.size()-1]->left =NULL;
        res[res.size()-1]->right = NULL;
    }
};
递归求解
下面用迭代求解,一步步的构造结点,由于题目是先序遍历,可以将右子树链接到左子树最右的孩子结点,如果不明白的可以手动模拟一下看与先序遍历是否相同,然后从根结点一步步往下构造
class Solution {
public:
    void flatten(TreeNode *root) {
        if(root == NULL) return;
        while(root){
            if(root->left){
                TreeNode* ptr = root->left;
                while(ptr->right) ptr = ptr->right;
                ptr->right = root->right;
                root->right = root->left;
                root->left = NULL;
            }
            root = root->right;
        }
    }
};

 


 

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

Leetcode Flatten Binary Tree to Linked List

标签:style   blog   http   color   os   art   

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3821054.html

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