js 实现二叉树中序遍历

2022/8/30 6:24:41

本文主要是介绍js 实现二叉树中序遍历,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

var inorderTraversal = function (root) {
    // 迭代
    if (!root) {
        return [];
    }
    let res = [];
    let stack = [];
    while (stack.length > 0) {
        // 循环遍历,将所有左节点push到栈中
        while (root) {
            stack.push(root);
            root = root.left;
        }
        // 取出 stack 最后 push 进去的节点
        const node = stack.pop();
        // 返回该节点的值
        res.push(node.val);
        // 每次取值的时候,将当前节点的右节点 push 到栈中
        root = node.right;
    }
    return res;
    // 递归
    // let res = [];
    // const inorder = (node, res) => {
    //     if (!node) {
    //         return res;
    //     }
    //     inorder(node.left, res);
    //     res.push(node.val);
    //     inorder(node.right, res);
    // };
    // inorder(root, res);
    // return res;
};

 



这篇关于js 实现二叉树中序遍历的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程