求二叉树的最大深度(JAVA)

求二叉树的最大深度(JAVA)

题目:

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

 1、递归法

如果我们知道了根节点的左子树的最大深度l和右子树的最大深度r,那么整颗树的深度可求得。Height = max(l,r)+1

求左子树和右子树的深度同上。

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            int leftHeight = maxDepth(root.left);
            int rightHeight = maxDepth(root.right);
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }
}

2、广度优先搜索

广度优先搜索的意思是先遍历根节点,在从左到右遍历完第二层,在接着遍历下一层直到遍历完整棵树。

基于广度优先算法的思想,我们利用队列来保存树的结点。

(1)首先,判断根节点是否为空。如果是为空,那么该树是空树,返回深度为0;否则,根节点不为空,将根节点送入队列中。

(2)循环判断队列是否为空。如果为空,该队列没有结点,表示广度遍历完了整棵树;否则,该队列不为空,获取队列的大小size(判断树每层结点的大小),到(3)。

(3)循环判断size>0。如果是,那么队列出队一次得到结点,判断该节点是否存在左右子树,如果是,那么将左右结点入队;

每出队一次,那么size--(相当于遍历完当前层的某个结点,当前层还剩多少个结点),直到当前层的结点遍历完size=0,

跳出循环(当前层的结点遍历完成),树的深度增加1。

public class HelloWorld {
    public static void main(String[] args) {
        TreeNoede root = new TreeNoede(3);
        TreeNoede a = new TreeNoede(9);
        root.left = a;
        TreeNoede b = new TreeNoede(20);
        root.right = b;
        TreeNoede c= new TreeNoede(15);
        b.left = c;
        TreeNoede d = new TreeNoede(7);
        b.right = d;
        int maxHeight = maxDepth(root);
        System.out.println(maxHeight);

    }

    public static int maxDepth(TreeNoede root){
        if(root == null){
            return 0;
        }else{
            int ans = 0;
            Queue<TreeNoede> queue = new LinkedList<TreeNoede>();
            queue.offer(root);
            while (!queue.isEmpty()){
                int size = queue.size();
                while (size>0){
                    TreeNoede p = queue.poll();
                    if(p.left != null){
                        queue.offer(p.left);
                    }
                    if(p.right != null){
                        queue.offer(p.right);
                    }
                    size--;
                }
                ans++;
            }
            return ans;
        }
    }

    }

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值