JavaScript实现二叉树中序遍历的两种方式

100 阅读1分钟
// 测试数据
const bt = {
    val: 1,
    left: {
        val: 2,
        left: {
            val: 4,
            left: null,
            right: null,
        },
        right: {
            val: 5,
            left: null,
            right: null,
        },
    },
    right: {
        val: 3,
        left: {
            val: 6,
            left: null,
            right: null,
        },
        right: {
            val: 7,
            left: null,
            right: null,
        },
    },
};
// 递归方式
const inorder = (root) => {
    if (!root) { return; }
    inorder(root.left);
    console.log(root.val);
    inorder(root.right);
};
// 非递归方式
const inorder = (root) => {
    if(!root) return
    const stack = [] // 定义一个栈,后进先出
    let p = root
    while(stack.length || p){ // 当栈为空 并且 p为空的时候说明已经完成整颗树的遍历
        while(p){
            stack.push(p) // 入栈
            p = p.left // 不停的访问左子树
        }
        const n  = stack.pop() // 出栈
        console.log(n.val)
        p = n.right // 访问右子树
    }
}