【树】树的中序遍历(非递归)

思路:先将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;
};

 

posted @ 2015-12-29 22:52  很好玩  阅读(474)  评论(0编辑  收藏  举报