美文网首页
前序,中序,后续遍历的非递归写法

前序,中序,后续遍历的非递归写法

作者: RedLee666 | 来源:发表于2019-08-18 10:01 被阅读0次

一、前序遍历

function preOrder(root) {
    let stack = [], res = [], p;
    stack.push(root);
    while (stack.length > 0) {
        p = stack.pop();
        if (p) {
            res.push(p.val);
            stack.push(p.right);
            stack.push(p.left);
        }
    }
    console.log(res.join('-'));
}

二、中序遍历

function inOrder(root) {
    let stack = [], res = [], p = root;
    while (p || stack.length > 0) {
        while (p) {
            stack.push(p);
            p = p.left;
        }
        p = stack.pop();
        res.push(p.val);
        p.right ? p = p.right : p = null;
    }
    console.log(res.join('-'));
}

三、后序遍历

function postOrder(root) {
    let stack = [], res = [], p = root;
    while (p || stack.length > 0) {
        while (p) {
            stack.push(p);
            p = p.left;
        }
        p = stack.pop();
        res.push(p.val);
        if (stack.length > 0 && p == stack[stack.length - 1].left)
            p = stack[stack.length - 1].right;
        else
            p = null;
    }
    console.log(res.join('-'));
}

相关文章

网友评论

      本文标题:前序,中序,后续遍历的非递归写法

      本文链接:https://www.haomeiwen.com/subject/bdfrsctx.html