二叉树的前序,中序,后序,层序实现

Posted strivegys

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树的前序,中序,后序,层序实现相关的知识,希望对你有一定的参考价值。

// 树根
function Tree(data,left,right) {
    this.data = data
    this.left = left
    this.right = right
    this.leftNode = Tree.leftNode
    this.rightNode = Tree.rightNode
    this.PreOrderTraversal = Tree.PreOrderTraversal
    this.MidOrderTraversal = Tree.MidOrderTraversal
    this.AfterOrderTraversal = Tree.AfterOrderTraversal
    this.InorderTraversal = Tree.InorderTraversal // 采用堆栈实现中序
    this.orderTraversal = Tree.orderTraversal;
}
// 左节点
Tree.leftNode = function(leftNode) {
    this.left = leftNode;
    return this;
}
// 右节点
Tree.rightNode = function(rightNode) {
    this.right = rightNode;
}
// 前序遍历
Tree.PreOrderTraversal = function(tree) {
    if(tree) {
        console.log(tree.data);
        this.PreOrderTraversal(tree.left);
        this.PreOrderTraversal(tree.right);
    }
}
// 中序遍历
Tree.MidOrderTraversal = function(tree) {
    if(tree) {
        this.MidOrderTraversal(tree.left);
        console.log(tree.data);
        this.MidOrderTraversal(tree.right);
    }
}
// 后序遍历
Tree.AfterOrderTraversal = function(tree) {
    if(tree) {
        this.AfterOrderTraversal(tree.left);
        this.AfterOrderTraversal(tree.right);
        console.log(tree.data);
    }
}

// 堆栈 非递归处理
Tree.InorderTraversal = function(tree) {
    let stack = [];
    while(tree || stack.length > 0) {
        while(tree) {
            console.log(tree.data);
            stack.push(tree);
            tree = tree.left;
        }
        if(stack.length > 0) {
            tree = stack.pop();
            // console.log(tree.data);
            tree = tree.right;
        }
    }
}

// 层序遍历输出
Tree.orderTraversal = function(tree) {
    let queue = [];
    if(!tree) return;
    queue.push(tree);
    while(queue.length > 0) {
        let tree = queue.shift()
        console.log(tree.data);
        if(tree.left) { queue.push(tree.left) }
        if(tree.right) { queue.push(tree.right) }
    }
}



let parent = new Tree(‘A‘);
let b = new Tree(‘B‘);
let c = new Tree(‘C‘);
let d = new Tree(‘D‘);
let e = new Tree(‘E‘);
let f = new Tree(‘F‘);
let g = new Tree(‘G‘);

parent.leftNode(b).rightNode(c);
b.leftNode(d).rightNode(e)
c.leftNode(f).rightNode(g)

console.log(‘先序遍历 == ‘);
parent.PreOrderTraversal(parent);
console.log(‘中序遍历 ==‘)
// parent.MidOrderTraversal(parent);
parent.InorderTraversal(parent);
console.log(‘后序遍历 ==‘)
parent.AfterOrderTraversal(parent);
console.log(‘层序遍历 == ‘)
parent.orderTraversal(parent);

 

以上是关于二叉树的前序,中序,后序,层序实现的主要内容,如果未能解决你的问题,请参考以下文章

Java实现二叉树的前序中序后序层序遍历(递归方法)

二叉树的前序中序后序层序遍历,递归和迭代两大类解题思路,每类细分不同解法完整版附PDF文档

二叉树的递归和非递归遍历(前序中序后序层序)

二叉树的前序遍历

二叉树的前序中序后序层次遍历的原理及C++代码实现

二叉树的前中后层序遍历