GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/src/MinimumDepthOfBinaryTree.java at master · LeBW/leetcode

Expand file tree

/

MinimumDepthOfBinaryTree.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
73 lines (67 loc) · 1.96 KB
/

MinimumDepthOfBinaryTree.java

Copy path

File metadata and controls

73 lines (67 loc) · 1.96 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.ArrayList;
import java.util.LinkedList;
/**
* 111. Minimum Depth of Binary Tree
* @author LBW
*/
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class MinimumDepthOfBinaryTree {
//递归DFS解法
private int result = Integer.MAX_VALUE;
public int minDepth(TreeNode root) {
if (root == null)
return 0;
result = Integer.MAX_VALUE;
dfs(root, 1);
return result;
}
private void dfs(TreeNode root, int depth) {
if (root.left == null && root.right == null) {
result = Math.min(result, depth);
}
if (root.left != null)
dfs(root.left, depth+1);
if (root.right != null)
dfs(root.right, depth+1);
}
//层序遍历解法
public int minDepthTwo(TreeNode root) {
//recursion version
// if (root == null)
// return 0;
// else if (root.left != null && root.right != null) {
// return 1 + min(run(root.left), run(root.right));
// }
// else {
// return 1 + max(run(root.left), run(root.right));
// }
if (root == null)
return 0;
ArrayList<TreeNode> arrayList = new ArrayList<>();
arrayList.add(root);
int depth = 0;
//层序遍历
while (!arrayList.isEmpty()) {
depth += 1;
int size = arrayList.size();
for (int i = 0; i < size; i++) {
if (arrayList.get(i).left == null && arrayList.get(i).right == null)
return depth;
if (arrayList.get(i).left != null)
arrayList.add(arrayList.get(i).left);
if (arrayList.get(i).right != null)
arrayList.add(arrayList.get(i).right);
}
for (int i = 0; i < size; i++)
arrayList.remove(0);
}
return depth;
}
}
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.