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

树的前序遍历(非递归)

时间:2015-12-30 00:23:06      阅读:212      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!