Skip to content

Commit 01a9adb

Browse files
committed
剑指 Offer 55 - I. 二叉树的深度
1 parent 192451d commit 01a9adb

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.geekidentity.leetcode.offer.backtracking;
2+
3+
/**
4+
* 搜索与回溯算法
5+
* 剑指 Offer 55 - I. 二叉树的深度
6+
* https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/
7+
*
8+
* 2 种解题方法
9+
*/
10+
public class Offer55IMaxDepth {
11+
private int depth = 0;
12+
13+
public int maxDepth(TreeNode root) {
14+
if (root == null) {
15+
return 0;
16+
}
17+
depth(root, 0);
18+
return depth;
19+
}
20+
21+
private void depth(TreeNode root, int d) {
22+
if (root == null) {
23+
if (d > depth) {
24+
depth = d;
25+
}
26+
return ;
27+
}
28+
depth(root.left, d + 1);
29+
depth(root.right, d + 1);
30+
}
31+
32+
public int maxDepth1(TreeNode root) {
33+
if (root == null) {
34+
return 0;
35+
}
36+
int left = maxDepth1(root.left);
37+
int right = maxDepth1(root.right);
38+
return Math.max(left, right) + 1;
39+
}
40+
private static class TreeNode {
41+
int val;
42+
TreeNode left;
43+
TreeNode right;
44+
TreeNode(int x) { val = x; }
45+
}
46+
}

0 commit comments

Comments
 (0)