二叉树节点类
/**
* 二叉树节点
*/
export default class TNode{
public value:number;
public left:TNode;
public right:TNode;
}
递归创建二叉树(先序建树)
/**
* 创建二叉树
* 以数组[1, 6, 0, 2, 3, 0, 4, 7, 0, 5]为例
* 1
* / \
*6 2
* / \
* 3 4
* / \
* 7 5
*
*/
createATree(arr: number[], head: TNode, index:number,s:string = ""):number {
head.value = arr[index++];
console.log(s + head.value);
if (index < arr.length) {
if (arr[index] !== 0){
head.left = new TNode();
index = this.createATree(arr, head.left,index, "左");
}else return ++index;
}
if (index < arr.length) {
if (arr[index] !== 0){
head.right = new TNode();
return this.createATree(arr, head.right,index, "右");
}else return ++index;
}
}
以数组 [1, 6, 0, 2, 3, 0, 4, 7, 0, 5] 为例,建成下图注释中的二叉树,
它的 递归序遍历 结果为 1 6 6 6 1 2 3 3 3 2 4 7 7 7 4 5 5 5 4 2 1
/**
* 递归序遍历
*
* 如:
* 1
* / \
*6 2
* / \
* 3 4
* / \
* 7 5
*
*/
printTreeInRecur(head: TNode) {
if (head != null) {
console.log(head.value) //第一次来到该节点时打印
this.printTreeInRecur(head.left);
console.log(head.value)//左子树递归完毕回到该节点时打印
this.printTreeInRecur(head.right);
console.log(head.value)//右子树递归完毕回到该节点时打印
}
}
它的先序遍历结果为 1 6 6 6 1 2 3 3 3 2 4 7 7 7 4 5 5 5 4 2 1 (黄色部分)
/**
* 先序遍历(递归)
* 对于每个节点而言都是 父节点->左节点->右节点 的顺序
*/
preorderPrintTreeInRecur(head: TNode) {
if (head != null) {
console.log(head.value) //第一次来到该节点时打印
this.preorderPrintTreeInRecur(head.left);
this.preorderPrintTreeInRecur(head.right);
}
}
它的中序遍历结果为 1 6 6 6 1 2 3 3 3 2 4 7 7 7 4 5 5 5 4 2 1(黄色部分)
/**
* 中序遍历(递归)
* 对于每个节点而言都是 左节点->父节点->右节点 的顺序
*/
middlePrintTreeInRecur(head: TNode) {
if (head != null) {
this.middlePrintTreeInRecur(head.left);
console.log(head.value) //左子树递归完毕回到该节点时打印
this.middlePrintTreeInRecur(head.right);
}
}
它的后序遍历结果为 1 6 6 6 1 2 3 3 3 2 4 7 7 7 4 5 5 5 4 2 1(黄色部分)
/**
* 后序遍历(递归)
* 对于每个节点而言都是 右节点->左节点->父节点 的顺序
*/
lastPrintTreeInRecur(head: TNode) {
if (head != null) {
this.lastPrintTreeInRecur(head.left);
this.lastPrintTreeInRecur(head.right);
console.log(head.value); //右子树递归完毕回到该节点时打印
}
}