1+ /* *
2+ * Definition for a binary tree node.
3+ * struct TreeNode {
4+ * int val;
5+ * TreeNode *left;
6+ * TreeNode *right;
7+ * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+ * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+ * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+ * };
11+ */
12+ class Solution {
13+ public:
14+ int minDepth (TreeNode* root) {
15+ if (root == nullptr ) return 0 ;
16+ if (root -> left == nullptr && root -> right == nullptr ) return 1 ;
17+ int left = numeric_limits<int >::max (), right = numeric_limits<int >::max ();
18+ if (root -> left != nullptr ) left = minDepth (root -> left);
19+ if (root -> right != nullptr ) right = minDepth (root -> right);
20+ return 1 + min (left, right);
21+ }
22+ };
23+
24+ /* ****************************************************************************************/
25+
26+ class Solution {
27+ public:
28+ void min_depth_util (TreeNode *root, int &min_depth, int depth = 1 ){
29+ if (root -> left == nullptr && root -> right == nullptr ){
30+ min_depth = min (min_depth, depth);
31+ return ;
32+ }
33+ if (depth >= min_depth) return ;
34+ if (root -> left != nullptr ) min_depth_util (root -> left, min_depth, depth + 1 );
35+ if (root -> right != nullptr ) min_depth_util (root -> right, min_depth, depth + 1 );
36+ }
37+ int minDepth (TreeNode* root) {
38+ if (root == nullptr ) return 0 ;
39+ int min_depth = numeric_limits<int >::max ();
40+ min_depth_util (root, min_depth);
41+ return min_depth;
42+ }
43+ };
44+
45+ /* ****************************************************************************************/
46+
47+ /* *
48+ * Definition for a binary tree node.
49+ * struct TreeNode {
50+ * int val;
51+ * TreeNode *left;
52+ * TreeNode *right;
53+ * TreeNode() : val(0), left(nullptr), right(nullptr) {}
54+ * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
55+ * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
56+ * };
57+ */
58+ class Solution {
59+ public:
60+ int minDepth (TreeNode* root) {
61+ if (root == nullptr ) return 0 ;
62+ queue <TreeNode*> q;
63+ map <TreeNode*, int > depths;
64+ q.push (root);
65+ depths[root] = 1 ;
66+ int depth = -1 ;
67+ while (!q.empty ()){
68+ TreeNode* current = q.front ();
69+ q.pop ();
70+ if (current -> left == nullptr && current -> right == nullptr ){
71+ depth = depths[current];
72+ break ;
73+ }
74+ if (current -> left != nullptr ){
75+ q.push (current -> left);
76+ depths[current -> left] = depths[current] + 1 ;
77+ }
78+ if (current -> right != nullptr ){
79+ q.push (current -> right);
80+ depths[current -> right] = depths[current] + 1 ;
81+ }
82+ }
83+ return depth;
84+ }
85+ };
0 commit comments