Java finds the maximum depth (tree height) of a binary tree
topic
Enter the root node of a binary tree and find the depth of the tree. The nodes passing through from the root node to the leaf node (including root and leaf nodes) form a path of the tree, and the length of the longest path is the depth of the tree.
example
Original title OJ link
https://leetcode.cn/problems/er-cha-shu-de-shen-du-lcof/
https://leetcode.cn/problems/maximum-depth-of-binary-tree/
answer
/**
* 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);
}
}