首页 > 其他 > 详细

树的前序遍历(非递归)

时间:2015-12-30 00:21:29      阅读:238      评论:0      收藏:0      [点我收藏+]

思路:将p入栈并访问p.val,遍历左子树;遍历完左子树返回时,栈顶元素应为p,出栈,再先序遍历p的右子树。

代码:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function(root) {
    if(root==null){
        return [];
    }
    if(root.left==null&&root.right==null){
        return [root.val];
    }
    var p=root,result=[],stack=[];
    
    while(p||stack.length!=0){
        if(p!=null){
            stack.push(p);
            result.push(p.val);
            p=p.left;
        }else{
            p=stack.pop();
            p=p.right;
        }
        
    }
    return result;
    
};

 

树的前序遍历(非递归)

原文:http://www.cnblogs.com/shytong/p/5087364.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!