java求二叉树的最大深度(树高)
java求二叉树的最大深度(树高)
题目
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
示例
原题OJ链接
https://leetcode.cn/problems/er-cha-shu-de-shen-du-lcof/
https://leetcode.cn/problems/maximum-depth-of-binary-tree/
解答
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.lang.Math;
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
if(root.right == null && root.left == null){
return 1;
}
// int count1 = maxDepth(root.left)+1;
// int count2 = maxDepth(root.right)+1;
// return Math.max(count1,count2);
return Math.max(maxDepth(root.left)+1, maxDepth(root.right)+1);
}
}
还没有评论,来说两句吧...