-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimum_Depth_of_Binary_Tree.cpp
More file actions
96 lines (83 loc) · 1.9 KB
/
Minimum_Depth_of_Binary_Tree.cpp
File metadata and controls
96 lines (83 loc) · 1.9 KB
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
// Source : https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/
// Author : zheng yi xiong
// Date : 2014-12-19
/**********************************************************************************
*
* 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.
*
**********************************************************************************/
#include "stdafx.h"
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int minDepth(TreeNode *root) {
if (NULL == root)
{
return 0;
}
int min_depth = 0, parent_num = 1, son_num = 0;
queue<TreeNode *> queue_node;
queue_node.push(root);
TreeNode *pNode = NULL;
while (!queue_node.empty())
{
pNode = queue_node.front();
queue_node.pop();
if (NULL == pNode->left && NULL == pNode->right)
{
++min_depth;
break;
}
if (NULL != pNode->left)
{
queue_node.push(pNode->left);
++son_num;
}
if (NULL != pNode->right)
{
queue_node.push(pNode->right);
++son_num;
}
--parent_num;
if (0 == parent_num)
{
++min_depth;
parent_num = son_num;
son_num = 0;
}
}
return min_depth;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
TreeNode node1(5);
TreeNode node2_1(4);
TreeNode node2_2(8);
TreeNode node3_1(11);
TreeNode node3_2(13);
TreeNode node3_3(4);
TreeNode node4_1(7);
TreeNode node4_2(2);
TreeNode node4_3(1);
node1.left = &node2_1;
node1.right = &node2_2;
node2_1.left = &node3_1;
node2_2.left = &node3_2;
node2_2.right = &node3_3;
node3_1.left = &node4_1;
node3_1.right = &node4_2;
node3_3.right = &node4_3;
Solution so;
int min_depth = so.minDepth(&node1);
return 0;
}