TS递归写二叉树先中后序遍历

二叉树节点类

/**
 * 二叉树节点
 */
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); //右子树递归完毕回到该节点时打印
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值