导航
导航
文章目录
  1. 翻译

LeetCode-104.Maximum Depth of Binary Tree

题目:
Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

翻译

给出一颗二叉树,找到他的最大深度。
最大深度是指从根节点到最远的叶子节点的最长路径上节点的数目。

递归求解,树的深度等于,左子树和右子树深度中较大的一个值,加1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);

return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;

}
}