剑指offer编程题(JAVA实现)——第38题:二叉树的深度

40 篇文章 1 订阅
40 篇文章 3 订阅


githubhttps://github.com/JasonZhangCauc/JZOffer
  • 剑指offer编程题(JAVA实现)——第38题:二叉树的深度
  • 题目描述
  • 输入一棵二叉树,求该树的深度。
  • 从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
public class Test38 {

	public static void main(String[] args) {
		
		

	}

	public int TreeDepth(TreeNode root) {
		
		return depth(root,0);
    }
	
	private int depth(TreeNode root, int i) {
		if (root == null) {
			return 0;
		}
		i = i + 1;
		TreeNode tmp = root;
		int left = 0;
		int right = 0;
		if (tmp.left != null) {
			left = depth(tmp.left, i);
		}

		if (tmp.right != null) {
			right = depth(tmp.right, i);
		}
		return Math.max(i, Math.max(left, right));
	}

	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 nLelt=TreeDepth(root.left);
        int nRight=TreeDepth(root.right);
         
        return nLelt>nRight?(nLelt+1):(nRight+1);
    }
}

*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花月诗人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值