shytong

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

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-12-10
  • 2022-01-24
  • 2022-02-13
  • 2021-11-07
猜你喜欢
  • 2022-02-25
  • 2022-02-05
  • 2021-11-21
  • 2022-12-23
  • 2022-02-08
  • 2022-01-11
  • 2021-11-20
相关资源
相似解决方案