94. 二叉树的中序遍历

62 阅读1分钟

给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。

示例 1:

image.png

输入: root = [1,null,2,3]
输出: [1,3,2]

示例 2:

输入: root = []
输出: []

题解:

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function (root) {
    // 中序遍历:左、中、右 
    // 方法一:递归
    // inorder(root) 根节点递归 
    // inorder(root.left) 递归左节点 
    // inorder(root.right) 递归右节点
    const stack = []
    const inorder = (root) => {
        if (!root) {
            return
        }
        inorder(root.left)
        stack.push(root.val)
        inorder(root.right)
    }
    inorder(root)
    return stack

    // 方法二:迭代
    // 头节点开始,每棵树的左节点入栈
    // 当节点为null时,出栈(打印即是中序)
    // 判断当前节点是否有右节点,
    // 有=》入栈(在判断当前节点是否有左节点),无=》继续出栈
    const stack = []
    const res = []
    while (stack.length || root) {
        if(root){
            stack.push(root)
            root = root.left
        }else{
            root = stack.pop()
            res.push(root.val)
            root = root.right
        }
    }
    return res
};