- 创建一棵树
//树的结构
function atree(value){
this.value=value
this.left=null
this.right=null
}
//构造一棵树
let a = new atree(4)
let b = new atree(6)
let c = new atree(8)
let d = new atree(5)
let e = new atree(9)
let f = new atree(1)
let g = new atree(2)
let h = new atree(5)
let i = new atree(3)
let j = new atree(2)
a.left=b
a.right=c
b.left=d
b.right=e
c.left=f
c.right=g
d.left=h
d.right=i
e.left=j
- 计算树的高度
//求树的深度
function deep(a){
if(!a){
return 0
}
if(!a.right){
return deep(a.left)+1
}
if(!a.left){
return deep(a.right)+1
}
return Math.max(deep(a.left),deep(a.right))+1
}
console.log('深度为 : ',deep(a))
- 深度优先:
先序遍历:先遍历根结点,然后左子树,再右子树
中序遍历:先遍历左子树,然后根结点,再右子树
后序遍历:先遍历左子树,然后右子树,再根结点
//先序遍历
function front(a,res=[]){
if(a!=null){
res.push(a.value) //数据保存,每次递归保存一个,其他交给下次迭代
if(a.left) front(a.left,res) //迭代带上唯一使用的数组
if(a.right) front(a.right,res)
}
return res
}
//中序遍历
function mid(a,res=[]){
if(a!=null){
if(a.left) mid(a.left,res)
res.push(a.value)
if(a.right) mid(a.right,res)
}
return res
}
//后序遍历
function behind(a,res=[]){
if(a!=null){
if(a.left) behind(a.left,res)
if(a.right) behind(a.right,res)
res.push(a.value)
}
return res
}
//debugger
console.log('先序遍历为 : ',front(a))
console.log('中序遍历为 : ',mid(a))
console.log('后序遍历为 : ',behind(a))
- 深度预先遍历,非递归
//深度优先遍历,非递归
function depthfirstsearch(a,res=[]){
if(a){
let tree = []
tree.push(a)
while(tree.length>0){
let node=tree.pop()
res.push(node.value)
//先入右子树
if(node.right){
tree.push(node.right)
}
if(node.left){
tree.push(node.left)
}
}
return res
}
}
console.log(depthfirstsearch(a))
- 广度优先遍历
//广度优先。非递归,好用的飞起
function widthfirst(a,res=[]){
if(a){
let tree = [] //队列中最多4个节点,最少0个;每次循环都出来一个,就能保证广度
tree.push(a)
while(tree.length>0){
let node = tree.shift()
res.push(node.value)
//选入左节点
if(node.left)tree.push(node.left)
if(node.right)tree.push(node.right)
}
return res
}
}
console.log(widthfirst(a))
-
二叉树中的所有路径
-
二叉树中和为某一值的路径
//关键点:一个存当前路径,一个存符合条件路径
let res = [] //放所有路径
let path = [] //存放当前路径
function FindPath(root, expectNumber)
{
if (!root) return res
path.push(root.value)
expectNumber = expectNumber-root.value
if ((expectNumber === 0) && (!root.left) && (!root.right)) {
res.push(...path) //push内容应该是数字,不能push数组
}
//防止超过expectnum但未到根节点时继续向下寻找,作无用的功
if(expectNumber<0 &&(root.left || root.right )){
path.pop()
return
}
if(root.left) FindPath(root.left, expectNumber)
if(root.right)FindPath(root.right, expectNumber)
path.pop()
return
}
FindPath(a,11)
console.log('path of 11',res)
FindPath(a,21)
console.log('path of 21',res)
- 给定一个二叉树, 找到该树中两个指定节点间的最短距离
- 哈夫曼树