TS写二叉树宽度优先遍历

深度优先遍历(DFS)分为先中后序遍历,在上一博文中已写到。
层次遍历即宽度优先遍历(BFS),是指按照从上到下的层级,每层从左到右来遍历二叉树。

	/**
     * 层次遍历 又名宽度优先遍历
     * 从上到下每一层地从左到右依次遍历
     * 如:
     *  1
     * / \
     *6   2
     *   / \
     *  3   4
     *     / \
     *    7   5
     * 遍历结果:1,6,2,3,4,7,5
     * 方法:使用队列(头进尾出)
     */
    printTreeInWidth(head: TNode) {
        let quene = [];
        quene.unshift(head);
        while (quene.length != 0) {
            let top = quene.pop(); //1.从队列中弹出一个节点
            console.log(top.value); //2.打印
            if (top.left) quene.unshift(top.left); //如果有 它的左子节点入列
            if (top.right) quene.unshift(top.right); //如果有 它的右子节点入列
        }
    }

延伸:求一棵二叉树的宽度

  /**
     * 求一棵二叉树的宽度(最大宽度)
     * 如:
     *     1
     *    / \
     *   6   2
     *  /   / \
     * 9   3   4
     *        / \
     *       7   5
     * 的最大宽度为3
     */
    getTreeMaxWidth(head:TNode){
        let quene = [];  //使用一个队列
        quene.unshift(head);
        let curLevEnd = head; //当前层最右边的节点
        let nextLevEnd = null; //下一层最右边的节点
        let curLevNodes = 0; //当前层所发现的节点数
        let max = 0; //最大宽度
        while(curLevEnd != null){
            let top = quene.pop();
            if(top.left != null){
                quene.unshift(top.left);
                nextLevEnd = top.left;
            } 
            if(top.right != null){
                quene.unshift(top.right);
                nextLevEnd = top.right;
            } 
            curLevNodes++;
            if(top == curLevEnd){
                max = Math.max(max,curLevNodes);
                curLevEnd = nextLevEnd;
                nextLevEnd = null;
                curLevNodes = 0;
            }
        }
        return max;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值