首页 > 其他 > 详细

树的中序遍历(非递归)

时间:2015-12-30 00:14:19      阅读:184      评论:0      收藏:0      [点我收藏+]

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

代码:

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

 

树的中序遍历(非递归)

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

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