码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-06-29 13:49:39      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:中序遍历   递归   span   new   tac   console   shift   二叉树   pop   

// 树根
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);

 

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

标签:中序遍历   递归   span   new   tac   console   shift   二叉树   pop   

原文地址:https://www.cnblogs.com/strivegys/p/13207401.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!