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

Leetcode--Flatten Binary Tree to Linked List

时间:2014-08-15 10:43:28      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:des   style   http   color   os   io   for   ar   

Problem Description:

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.

分析:按照题目的意思,将二叉树变为按先序序列排列的极端右子树形式,因此解题思路就是将二叉树按照先序遍历先把节点保存下来,然后按照要求重建二叉树即可,实际中采用了非递归的先序遍历,将节点保存到vector中,最后将重建二叉树。具体代码如下:

/**
 * Definition for binary tree
 * 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==NULL)
            return;
        vector<TreeNode *> vec;
        stack<TreeNode *> stk;
        TreeNode *p=root;
        while(p||!stk.empty())
        {
            while(p)
            {
                vec.push_back(p);
                stk.push(p);
                p=p->left;
            }
            if(!stk.empty())
            {
                p=stk.top();
                stk.pop();
                p=p->right;
            }
        }
        root=vec[0];
        for(int i=0;i<vec.size()-1;i++)
        {
            vec[i]->left=NULL;
            vec[i]->right=vec[i+1];
        }
        vec[vec.size()-1]->left=NULL;
        vec[vec.size()-1]->right=NULL;
    }
};

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

Leetcode--Flatten Binary Tree to Linked List

标签:des   style   http   color   os   io   for   ar   

原文地址:http://blog.csdn.net/longhopefor/article/details/38581147

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