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

思路:先将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;
};
原文地址:https://www.cnblogs.com/shytong/p/5087375.html