Skip to content
文档章节

BM24 二叉树的中序遍历

1. 递归

2. 堆栈法

  1. 指针p指向root节点
  2. p如果节点有左子树,左子树入栈, p 指向左子树, 重复此步骤
  3. stack 出栈, 访问当前节点node,p指向node节点右子树
  4. 重复2-3 步骤
ts
/*class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param root TreeNode类
 * @return int整型一维数组
 */
export function inorderTraversal(root: TreeNode): number[] {
  // write code here
    var res:number[] = [];
    var stack: TreeNode[] = [];
    if(!root) return res;
    
    while(root || stack.length) {
        while(root) {
            stack.push(root);
            root = root.left;
        }
        
        var node = stack.pop();
        res.push(node.val)
        root = node.right;
    }
    return res;
}