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

【树】Flatten Binary Tree to Linked List(先序遍历)

时间:2016-01-29 20:51:37      阅读:215      评论: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.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
var flatten = function(root) {
    if(root==null){
        return;
    }
    var stack=[],pre=null;
    stack.push(root);
    
    while(stack.length!=0){
        var p=stack.pop();
        if(pre!=null){
            pre.right=p;
            pre.left=null
        }
        if(p.right){
            stack.push(p.right);
        }
        if(p.left){
            stack.push(p.left);
        }
        pre=p;
    }
    
    pre.left=null;
    pre.right=null;
};

 

【树】Flatten Binary Tree to Linked List(先序遍历)

标签:

原文地址:http://www.cnblogs.com/shytong/p/5169831.html

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