File tree Expand file tree Collapse file tree 3 files changed +74
-0
lines changed Expand file tree Collapse file tree 3 files changed +74
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Solve Time : 07:17
3
+
4
+ Time : O(V + E)
5
+ Space : O(V)
6
+
7
+ root ~ leafまでの距離、という部分を読み違えて時間を多少ロスしたものの、特につまるところなく解けた。
8
+ */
9
+ class Solution {
10
+ public:
11
+ int minDepth (TreeNode* root) {
12
+ queue<pair<TreeNode*, int >> nodes_and_depths;
13
+ nodes_and_depths.emplace (root, 1 );
14
+ while (!nodes_and_depths.empty ()) {
15
+ auto [node, depth] = nodes_and_depths.front ();
16
+ nodes_and_depths.pop ();
17
+ if (!node) {
18
+ continue ;
19
+ }
20
+ if (node->left == nullptr && node->right == nullptr ) {
21
+ return depth;
22
+ }
23
+ nodes_and_depths.emplace (node->left , depth + 1 );
24
+ nodes_and_depths.emplace (node->right , depth + 1 );
25
+ }
26
+ return 0 ;
27
+ }
28
+ };
Original file line number Diff line number Diff line change
1
+ /*
2
+ Time : O(V + E)
3
+ Space : O(V)
4
+
5
+ 再帰,DFSで解いてみる。
6
+ rootの処理をどうしても分岐で処理できなかったので最初のrootの面倒を見る関数と再帰処理をする関数とに分けた。
7
+ */
8
+ class Solution {
9
+ public:
10
+ int minDepth (TreeNode* root) {
11
+ if (!root) {
12
+ return 0 ;
13
+ }
14
+ return minDepthRecursive (root);
15
+ }
16
+ private:
17
+ int minDepthRecursive (TreeNode* root) {
18
+ if (!root) {
19
+ return numeric_limits<int >::max ();
20
+ }
21
+ if (root->left == nullptr && root->right == nullptr ) {
22
+ return 1 ;
23
+ }
24
+ return min (minDepthRecursive (root->left ), minDepthRecursive (root->right )) + 1 ;
25
+ }
26
+ };
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int minDepth (TreeNode* root) {
4
+ queue<pair<TreeNode*, int >> nodes_and_depths;
5
+ nodes_and_depths.emplace (root, 1 );
6
+ while (!nodes_and_depths.empty ()) {
7
+ auto [node, depth] = nodes_and_depths.front ();
8
+ nodes_and_depths.pop ();
9
+ if (!node) {
10
+ continue ;
11
+ }
12
+ if (!(node->left || node->right )) {
13
+ return depth;
14
+ }
15
+ nodes_and_depths.emplace (node->left , depth + 1 );
16
+ nodes_and_depths.emplace (node->right , depth + 1 );
17
+ }
18
+ return 0 ;
19
+ }
20
+ };
You can’t perform that action at this time.
0 commit comments