树
深度优先搜索
广度优先搜索
二叉树
题目描述
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例 1:
输入: root = [3,9,20,null,null,15,7]
输出: 2
示例 2:
输入: root = [2,null,3,null,4,null,5,null,6]
输出: 5
提示:
树中节点数的范围在 [0, 105 ]
内
-1000 <= Node.val <= 1000
解法
方法一:递归
递归的终止条件是当前节点为空,此时返回 $0$;如果当前节点左右子树有一个为空,返回不为空的子树的最小深度加 $1$;如果当前节点左右子树都不为空,返回左右子树最小深度的较小值加 $1$。
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。
Python3 Java C++ Go TypeScript Rust JavaScript C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution :
def minDepth ( self , root : Optional [ TreeNode ]) -> int :
if root is None :
return 0
if root . left is None :
return 1 + self . minDepth ( root . right )
if root . right is None :
return 1 + self . minDepth ( root . left )
return 1 + min ( self . minDepth ( root . left ), self . minDepth ( root . right ))
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 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth ( TreeNode root ) {
if ( root == null ) {
return 0 ;
}
if ( root . left == null ) {
return 1 + minDepth ( root . right );
}
if ( root . right == null ) {
return 1 + minDepth ( root . left );
}
return 1 + Math . min ( minDepth ( root . left ), minDepth ( root . right ));
}
}
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 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public :
int minDepth ( TreeNode * root ) {
if ( ! root ) {
return 0 ;
}
if ( ! root -> left ) {
return 1 + minDepth ( root -> right );
}
if ( ! root -> right ) {
return 1 + minDepth ( root -> left );
}
return 1 + min ( minDepth ( root -> left ), minDepth ( root -> right ));
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 /**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minDepth ( root * TreeNode ) int {
if root == nil {
return 0
}
if root . Left == nil {
return 1 + minDepth ( root . Right )
}
if root . Right == nil {
return 1 + minDepth ( root . Left )
}
return 1 + min ( minDepth ( root . Left ), minDepth ( root . Right ))
}
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 /**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function minDepth ( root : TreeNode | null ) : number {
if ( root == null ) {
return 0 ;
}
const { left , right } = root ;
if ( left == null ) {
return 1 + minDepth ( right );
}
if ( right == null ) {
return 1 + minDepth ( left );
}
return 1 + Math . min ( minDepth ( left ), minDepth ( right ));
}
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 // Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std :: cell :: RefCell ;
use std :: rc :: Rc ;
impl Solution {
fn dfs ( root : & Option < Rc < RefCell < TreeNode >>> ) -> i32 {
if root . is_none () {
return 0 ;
}
let node = root . as_ref (). unwrap (). borrow ();
if node . left . is_none () {
return 1 + Self :: dfs ( & node . right );
}
if node . right . is_none () {
return 1 + Self :: dfs ( & node . left );
}
1 + Self :: dfs ( & node . left ). min ( Self :: dfs ( & node . right ))
}
pub fn min_depth ( root : Option < Rc < RefCell < TreeNode >>> ) -> i32 {
Self :: dfs ( & root )
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function ( root ) {
if ( ! root ) {
return 0 ;
}
if ( ! root . left ) {
return 1 + minDepth ( root . right );
}
if ( ! root . right ) {
return 1 + minDepth ( root . left );
}
return 1 + Math . min ( minDepth ( root . left ), minDepth ( root . right ));
};
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 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#define min(a, b) (((a) < (b)) ? (a) : (b))
int minDepth ( struct TreeNode * root ) {
if ( ! root ) {
return 0 ;
}
if ( ! root -> left ) {
return 1 + minDepth ( root -> right );
}
if ( ! root -> right ) {
return 1 + minDepth ( root -> left );
}
int left = minDepth ( root -> left );
int right = minDepth ( root -> right );
return 1 + min ( left , right );
}
方法二:BFS
使用队列实现广度优先搜索,初始时将根节点加入队列。每次从队列中取出一个节点,如果该节点是叶子节点,则直接返回当前深度;如果该节点不是叶子节点,则将该节点的所有非空子节点加入队列。继续搜索下一层节点,直到找到叶子节点。
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。
Python3 Java C++ Go TypeScript JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution :
def minDepth ( self , root : Optional [ TreeNode ]) -> int :
if root is None :
return 0
q = deque ([ root ])
ans = 0
while 1 :
ans += 1
for _ in range ( len ( q )):
node = q . popleft ()
if node . left is None and node . right is None :
return ans
if node . left :
q . append ( node . left )
if node . right :
q . append ( node . right )
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 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth ( TreeNode root ) {
if ( root == null ) {
return 0 ;
}
Deque < TreeNode > q = new ArrayDeque <> ();
q . offer ( root );
int ans = 0 ;
while ( true ) {
++ ans ;
for ( int n = q . size (); n > 0 ; n -- ) {
TreeNode node = q . poll ();
if ( node . left == null && node . right == null ) {
return ans ;
}
if ( node . left != null ) {
q . offer ( node . left );
}
if ( node . right != null ) {
q . offer ( node . right );
}
}
}
}
}
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 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public :
int minDepth ( TreeNode * root ) {
if ( ! root ) {
return 0 ;
}
queue < TreeNode *> q {{ root }};
int ans = 0 ;
while ( 1 ) {
++ ans ;
for ( int n = q . size (); n ; -- n ) {
auto node = q . front ();
q . pop ();
if ( ! node -> left && ! node -> right ) {
return ans ;
}
if ( node -> left ) {
q . push ( node -> left );
}
if ( node -> right ) {
q . push ( node -> right );
}
}
}
}
};
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 /**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minDepth ( root * TreeNode ) ( ans int ) {
if root == nil {
return 0
}
q := [] * TreeNode { root }
for {
ans ++
for n := len ( q ); n > 0 ; n -- {
node := q [ 0 ]
q = q [ 1 :]
if node . Left == nil && node . Right == nil {
return
}
if node . Left != nil {
q = append ( q , node . Left )
}
if node . Right != nil {
q = append ( q , node . Right )
}
}
}
}
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 /**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function minDepth ( root : TreeNode | null ) : number {
if ( ! root ) {
return 0 ;
}
const q = [ root ];
let ans = 0 ;
while ( 1 ) {
++ ans ;
for ( let n = q . length ; n ; -- n ) {
const node = q . shift ();
if ( ! node . left && ! node . right ) {
return ans ;
}
if ( node . left ) {
q . push ( node . left );
}
if ( node . right ) {
q . push ( node . right );
}
}
}
}
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 /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function ( root ) {
if ( ! root ) {
return 0 ;
}
const q = [ root ];
let ans = 0 ;
while ( 1 ) {
++ ans ;
for ( let n = q . length ; n ; -- n ) {
const node = q . shift ();
if ( ! node . left && ! node . right ) {
return ans ;
}
if ( node . left ) {
q . push ( node . left );
}
if ( node . right ) {
q . push ( node . right );
}
}
}
};