Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit962f5e4

Browse files
author
applewjg
committed
max/min depth of BT
Change-Id: I012c63ec71667163a04fc9194f3f08937aaeea6b
1 parentf81c713 commit962f5e4

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, wangjingui@outlook.com
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+
publicclassSolution {
23+
publicintmaxDepth(TreeNoderoot) {
24+
if (root ==null)return0;
25+
intleft =maxDepth(root.left);
26+
intright =maxDepth(root.right);
27+
returnMath.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, wangjingui@outlook.com
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+
publicclassSolution {
26+
publicintminDepth(TreeNoderoot) {
27+
if (root ==null)return0;
28+
if (root.left ==null)returnminDepth(root.right) +1;
29+
if (root.right ==null)returnminDepth(root.left) +1;
30+
returnMath.min(minDepth(root.left),minDepth(root.right)) +1;
31+
}
32+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp