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
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

public class Solution {

public int maxDepth(TreeNode root) {

//初次提交忘记提交该判断。

if(root==null){

return 0;

}

return g(root,1);

}

//这里depth为该tn节点的深度,如果tn没子节点,则直接返回

public int g(TreeNode tn,int depth){

TreeNode leftNode = tn.left;

TreeNode rigthNode = tn.right;

int leftL = depth;

int rightL = depth;

if(leftNode!=null){

leftL = g(leftNode,depth+1);

}

if(rigthNode!=null){

rightL = g(rigthNode,depth+1);

}

return leftL>rightL?leftL:rightL;

}

}