JavaScript的二叉树遍历

JavaScript的二叉树遍历

参考博客:https://www.jianshu.com/p/5e9ea25a1aae

1.前序遍历(根左右)

const result = [];
//前序遍历
function preOrderTraversal(node){
    if(node){
        result.push(node.value);
        if(node.left) preOrderTraversal(node.left);
        if(node.right) preOrderTraversal(node.right);
    }
}
//前序遍历非递归
function preOrderTraversalNonRecursive(nodes){
    const stack = [];
    stack.push(nodes);
    while(stack.length){
        let node = stack.pop();
        result.push(node.value);
        if(node.right) stack.push(node.right);
        if(node.left) stack.push(node.left);
    }
}

2.中序遍历(左根右)

const result = [];
//中序遍历
function inOrderTraversal(node) {
    if(node){
        if(node.left) inOrderTraversal(node.left);
        result.push(node.value);
        if(node.right) inOrderTraversal(node.right);
    }
}
//中序遍历非递归
function inOrderTraversalNonRecursive(node) {
    const stack = [];
    while(stack.length || node) {
        if(node) {
            stack.push(node);
            node = node.left;
        }
        else {
            node = stack.pop();
            result.push(node.value);
            node = node.right;
        }
    }
}

3.后序遍历(左右根)

const result = [];
//后序遍历
function postOrderTraversal(node) {
    if(node){
        if(node.left) postOrderTraversal(node.left);
        if(node.right) postOrderTraversal(node.right);
        result.push(node.value);
    }
}
//后序遍历非递归
function postOrderTraversalNonRecursive(node) {
    const stack = [];
    stack.push(node);
    while(stack.length) {
        if(node.left && !node.touched) {
            node.touched = 'left';
            node = node.left;
            stack.push(node);
            continue;
        }
        if(node.right && node.touched !== 'right') {
            node.touched = 'right';
            node = node.right;
            stack.push(node);
            continue;
        }
        node = stack.pop();
        node.touched && delete node.touched;
        result.push(node.value);
        node = stack.length ? stack[stack.length - 1] : null;
    }
}

4.层次遍历

//层次遍历
const result = [];
const stack = [tree];//tree为整个二叉树结构
let count = 0;
function levelOrderTraversal() {
    let node = stack[count];
    if(node) {
        result.push(node.value);
        if(node.left) stack.push(node.left);
        if(node.right) stack.push(node.right);
        count++;
        levelOrderTraversal();
    }
}
//层次遍历非递归
function levelOrderTraversalNonRecursive(node) {
    const queue = [];
    queue.push(node);
    let pointer = 0;
    while(pointer < queue.length) {
        let node = queue[pointer++];
        result.push(node.value);
        node.left && queue.push(node.left);
        node.right && queue.push(node.right);
    }
}

你可能感兴趣的:(JavaScript)