Skip to content

Commit 962f5e4

Browse files
author
applewjg
committed
max/min depth of BT
Change-Id: I012c63ec71667163a04fc9194f3f08937aaeea6b
1 parent f81c713 commit 962f5e4

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

MaximumDepthofBinaryTree.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 25, 2014
4+
Problem: Maximum Depth of Binary Tree
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/
7+
Notes:
8+
Given a binary tree, find its maximum depth.
9+
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
10+
11+
Solution: Recursion.
12+
*/
13+
/**
14+
* Definition for binary tree
15+
* public class TreeNode {
16+
* int val;
17+
* TreeNode left;
18+
* TreeNode right;
19+
* TreeNode(int x) { val = x; }
20+
* }
21+
*/
22+
public class Solution {
23+
public int maxDepth(TreeNode root) {
24+
if (root == null) return 0;
25+
int left = maxDepth(root.left);
26+
int right = maxDepth(root.right);
27+
return Math.max(left, right) + 1;
28+
}
29+
}

MinimumDepthofBinaryTree.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 25, 2014
4+
Problem: Minimum Depth of Binary Tree
5+
Difficulty: easy
6+
Source: https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/
7+
Notes:
8+
Given a binary tree, find its minimum depth.
9+
The minimum depth is the number of nodes along the shortest path from the root node
10+
down to the nearest leaf node.
11+
12+
Solution: 1. Recursion. Pay attention to cases when the non-leaf node has only one child.
13+
PS. 2. Iteration + Queue.
14+
*/
15+
16+
/**
17+
* Definition for binary tree
18+
* public class TreeNode {
19+
* int val;
20+
* TreeNode left;
21+
* TreeNode right;
22+
* TreeNode(int x) { val = x; }
23+
* }
24+
*/
25+
public class Solution {
26+
public int minDepth(TreeNode root) {
27+
if (root == null) return 0;
28+
if (root.left == null) return minDepth(root.right) + 1;
29+
if (root.right == null) return minDepth(root.left) + 1;
30+
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
31+
}
32+
}

0 commit comments

Comments
 (0)