二叉树的前中后序非递归遍历

208 阅读1分钟
/**
 * 非递归形式前中后序遍历
 */
 
 // 前序遍历很好理解,利用一个栈
function preSearch(root, callback) {
    const stack = [root];

    while(stack.length !== 0) {
        const node = stack.pop();

        // 处理逻辑
        console.log(node.val);
        callback(node);
        // 先右后左
        if (node.rightChild) stack.push(node.rightChild);
        if (node.leftChild) stack.push(node.leftChild);
    }
}

function midSearch(root, callback) {
    const stack = [];

    let nowNode = root;

    while(stack.length !== 0 || nowNode !== null) {
        // 从左路一直走到底
        while (nowNode !== null) {
            stack.push(nowNode);
            nowNode = nowNode.leftChild;
        }
        if (stack.length !== 0) {
            // 到底之后就输出该节点
            nowNode = stack.pop();
        
            // 处理逻辑
            console.log(nowNode.val);
            callback(nowNode);
            // 该节点的左孩子都结束了,开始右孩子
            nowNode = nowNode.rightChild;
        }
    }
}

function backSearch(root) {
    const stack = [];
    const output = [];
    /* 1 */
    /*
    let nowNode = root;
    while(stack.length !== 0 || nowNode !== null) {
        if  (nowNode !== null) {
            stack.push(nowNode);
            output.push(nowNode);
            nowNode = nowNode.rightChild;
        } else {
            nowNode = stack.pop()
            nowNode = nowNode.leftChild;
        }
    }

    while (output.length !== 0) {
        console.log(output.pop().val)
    }
    */
    /* 1 end */

    /* 2 */
    // 跟前序遍历差不多
    stack.push(root);
    while(stack.length !== 0) {
        const node = stack.pop();
        // 从头插入
        output.unshift(node);
        // 跟前序遍历相仿,先左后右
        if (node.leftChild) stack.push(node.leftChild);
        if (node.rightChild) stack.push(node.rightChild);
    }
    while (output.length !== 0) {
        console.log(output.shift().val)
    }
}