-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimumDepthOfBinaryTree.h
102 lines (83 loc) · 2.85 KB
/
MinimumDepthOfBinaryTree.h
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
Author: naiyong, aonaiyong@gmail.com
Date: Sep 24, 2014
Problem: Minimum Depth of Binary Tree
Difficulty: 1
Source: https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/
Notes:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Solution: 1. Recursive Post-order Traversal.
Time: O(n), Space: O(n).
2. Iterative Post-order Traversal.
Time: O(n), Space: O(n).
3. Iterative Level-order Traversal.
Time: O(n), Space: O(n).
This solution is the most efficient one.
*/
#ifndef MINIMUMDEPTHOFBINARYTREE_H_
#define MINIMUMDEPTHOFBINARYTREE_H_
#include <algorithm>
using std::min;
#include <climits>
#include <stack>
using std::stack;
#include <queue>
using std::queue;
#include "TreeNode.h"
class Solution {
public:
int minDepth(TreeNode *root) {
return iterativeStackMinDepth(root);
}
int recursiveMinDepth(TreeNode *root) {
if (!root) return 0;
if (!root->left) return 1 + recursiveMinDepth(root->right);
if (!root->right) return 1 + recursiveMinDepth(root->left);
int leftMin = recursiveMinDepth(root->left);
int rightMin = recursiveMinDepth(root->right);
return 1 + min(leftMin, rightMin);
}
int iterativeStackMinDepth(TreeNode *root) {
if (!root) return 0;
int minDepth = INT_MAX;
stack<TreeNode *> stk;
TreeNode *node = root, *lastNodeVisited = nullptr;
while (node || !stk.empty()) {
if (node) {
stk.push(node);
node = node->left;
}
else {
TreeNode *peakNode = stk.top();
if (!peakNode->right || peakNode->right == lastNodeVisited) {
if (!peakNode->right && !peakNode->left)
minDepth = min(minDepth, static_cast<int>(stk.size()));
lastNodeVisited = peakNode;
stk.pop();
}
else
node = peakNode->right;
}
}
return minDepth;
}
int iterativeQueueMinDepth(TreeNode *root) {
int minDepth = 0;
queue<TreeNode *> frontier;
if (root) frontier.push(root);
while (!frontier.empty()) {
++minDepth;
int n = frontier.size();
for (int i = 0; i < n; ++i) {
TreeNode *node = frontier.front();
if (!node->left && !node->right) return minDepth;
if (node->left) frontier.push(node->left);
if (node->right) frontier.push(node->right);
frontier.pop();
}
}
return minDepth;
}
};
#endif /* MINIMUMDEPTHOFBINARYTREE_H_ */