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

[leetcode]Flatten Binary Tree to Linked List

时间:2015-01-14 22:54:05      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

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.

代码:

void flatten(TreeNode *root) {  //C++
        if(root == NULL)
            return;
        stack<TreeNode* > myStack;
        queue<TreeNode* > myQueue;
        
        TreeNode *p = root;
        while(p!=NULL || !myStack.empty())
        {
            while(p!=NULL){
                myQueue.push(p);
                myStack.push(p);
                p=p->left;
            }
            p = myStack.top();
            myStack.pop();
            p = p->right;
        }
        
        p = myQueue.front();
        myQueue.pop();
        
        while(!myQueue.empty()){
            TreeNode* temp = myQueue.front();
            p->right = temp;
            p->left = NULL;
            p = temp;
            myQueue.pop();
        }
        
    }


[leetcode]Flatten Binary Tree to Linked List

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/42718277

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