js 二叉树实现前序遍历、中序吧遍历、后序遍历

js 二叉树实现前序遍历、中序吧遍历、后序遍历

定义二叉树


//定义二叉树
function Node(value) {
     
    this.value = value;
    this.left = null;
    this.right = null;
}

var a = new Node("a")
var b = new Node('b')
var c = new Node("c")
var d = new Node("d")
var e = new Node("e")
var f = new Node("f")

a.left = b
a.right = c
b.left = d
b.right = e
c.left = f

console.log(a)

前序遍历



//前序遍历
function VLR(root) {
     
    if(root === null) return
    console.log(root.value)
    VLR(root.left)
    VLR(root.right)
}
console.log("前序 遍历")
VLR(a)

中序遍历



//中序遍历
function LDR(root) {
     
    if(root === null) return
    LDR(root.left)
    console.log(root.value)
    LDR(root.right)
}
console.log("中序 遍历")
LDR(a)

后序遍历



//后序遍历
function LRD(root) {
     
    if (root === null) return;
    LRD(root.left)
    LRD(root.right)
    console.log(root.value)
}
console.log("后序遍历")
LRD(a)

你可能感兴趣的:(算法,JavaScript,js,算法)