剑指offer 二叉树的深度 Java

本文介绍了两种计算二叉树深度的方法:递归方法和非递归的BFS方法。递归方法通过比较左右子树深度并加一得到整棵树的深度;非递归方法使用队列进行广度优先搜索,每遍历完一层节点,深度加一。

递归写法

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        return Math.max(left,right)+1;
        
    }
}

非递归 BFS实现

import java.util.*;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int size,level = 0;
        TreeNode now;
        while(!queue.isEmpty()){
            level++;
            size = queue.size();
            while(size --> 0){
                now = queue.poll();
                if(now.left != null) queue.offer(now.left);
                if(now.right != null) queue.offer(now.right);
            }
        }
        return level;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值