leetcode [#104]

目录

题目

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 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) {
int depth = 0;
if(root == null){
return depth;
} else {
int l = 0;
int r = 0;
if(root.left != null){
l = maxDepth(root.left);
}
if(root.right != null){
r = maxDepth(root.right);
}
depth = l > r ? l : r;
return depth + 1;
}
}
}

注意事项

  思路是递归,根据二叉树的结构,某个子节点是其子树的根节点,则不断反复进行递归直到找到叶子节点,返回为零,其余不断加1,累计总长度(左右子节点均相同处理)。