【leetcode-每日一题】计算二叉树的深度

递归实现

思路
1.若根节点是空节点,则为空树,深度为0;

2.若根节点不为空,则选择左子树和右子树中深度大的为新树,原树的深度是新树的深度+1;

 /**
     * 递归实现 计算二叉树深度
     *
     * @param treeNode 二叉树
     * @return 二叉树深度
     */
    public int getBinTreeDepthRecursion(TreeNode treeNode) {
        if (treeNode == null) {
            return 0;
        }
        //左子树
        int left = getBinTreeDepthRecursion(treeNode.getLeftChild());
        //右子树
        int right = getBinTreeDepthRecursion(treeNode.getRightChild());
       // System.out.println("left=" + left + ", right=" + right);
        return left > right ? left + 1 : right + 1;
    }

层序遍历

 /**
     * 层序遍历实现计算二叉树深度
     * @param treeNode 二叉树
     * @return 二叉树深度
     */
    public int getBinTreeDepthLevelOrderTraversal(TreeNode treeNode) {
        if (treeNode == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        //将指定的元素插入此队列(如果立即可行且不会违反容量限制),
        // 当使用有容量限制的队列时,此方法通常要优于 add(E),后者可能无法插入元素,而只是抛出一个异常。
        queue.offer(treeNode);
        //记录当前层的个数
        int nextCount = 1;
        int count = 0;
        //记录层数
        int deep = 0;
        while (!queue.isEmpty()) {
            //获取并移除此队列的头,如果此队列为空,则返回 null
            TreeNode node = queue.poll();
            count++;
            if (node.getLeftChild() != null) {
                queue.offer(node.getLeftChild());
            }
            if (node.getRightChild() != null) {
                queue.offer(node.getRightChild());
            }
            if (count==nextCount){
                nextCount=queue.size();
                count=0;
                deep++;
            }
        }
        return deep;
    }

TreeNode

package com.edu.BinaryTree;

/**
 * @Date 2020/5/25 16:47
 * @Author by hp
 * @Description 二叉树对象
 */
public class TreeNode {
    private int data;
    //左节点
    private TreeNode leftChild;
    //右节点
    private  TreeNode rightChild;

    public TreeNode(int data) {
        this.data = data;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public TreeNode getLeftChild() {
        return leftChild;
    }

    public void setLeftChild(TreeNode leftChild) {
        this.leftChild = leftChild;
    }

    public TreeNode getRightChild() {
        return rightChild;
    }

    public void setRightChild(TreeNode rightChild) {
        this.rightChild = rightChild;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值