File tree Expand file tree Collapse file tree 3 files changed +78
-2
lines changed Expand file tree Collapse file tree 3 files changed +78
-2
lines changed Original file line number Diff line number Diff line change @@ -81,5 +81,8 @@ unlike normal projects.
81
81
* [ Util ContainersToString] ( https://github.com/jljacoblo/jalgorithmCPP/blob/master/src/String/ContainersToString.h )
82
82
* [ Sherlock and the Valid String] ( https://github.com/jljacoblo/jalgorithmCPP/blob/master/src/String/SherlockValidString.h )
83
83
* [ Unique Emails - LeetCode] ( https://github.com/jljacoblo/jalgorithmCPP/blob/master/src/String/UniqueEmails.h )
84
-
85
84
***
85
+
86
+ #### Tree
87
+ * [ FlattenBinaryTreeToList - LeetCode MEDIUM] ( https://github.com/jljacoblo/jalgorithmCPP/blob/master/src/Tree/FlattenBinaryTreeList.h )
88
+ ***
8000
Original file line number Diff line number Diff line change @@ -55,5 +55,5 @@ add_executable(jalgorithmCPP
55
55
Heap/KClosest.h
56
56
Dictionary/SubdomainVisitCount.h
57
57
String /UniqueEmails.h
58
- )
58
+ Tree /FlattenBinaryTreeList.h )
59
59
Original file line number Diff line number Diff line change
1
+ //
2
+ // Created by Jacob Lo on Jan 18, 2019
3
+ //
4
+
5
+ // MEDIUM
6
+ // https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
7
+ // Given a binary tree, flatten it to a linked list in-place.
8
+ //
9
+ // For example, given the following tree:
10
+ //
11
+ // 1
12
+ // / \
13
+ // 2 5
14
+ // / \ \
15
+ //3 4 6
16
+ // The flattened tree should look like:
17
+ //
18
+ // 1
19
+ // \
20
+ // 2
21
+ // \
22
+ // 3
23
+ // \
24
+ // 4
25
+ // \
26
+ // 5
27
+ // \
28
+ // 6
29
+
30
+ #pragma once
31
+
32
+
33
+ namespace FlattenBinaryTreeList {
34
+ struct TreeNode {
35
+ int val;
36
+ TreeNode *left;
37
+ TreeNode *right;
38
+
39
+ TreeNode (int x) : val(x), left(nullptr ), right(nullptr ) {}
40
+ };
41
+
42
+ TreeNode *flattenRec (TreeNode *n) {
43
+
44
+ if (!n) return nullptr ;
45
+
46
+ TreeNode *listedRight = flattenRec (n->right );
47
+
48
+ // / if no child, or only right child
49
+ if (!n->left ) {
50
+ n->right = listedRight;
51
+ return n;
52
+ }
53
+
54
+ TreeNode *listedLeft = flattenRec (n->left );
55
+
56
+ TreeNode *lastOfRightNodeInListedLeft = listedLeft;
57
+ while (lastOfRightNodeInListedLeft->right != nullptr ) {
58
+ lastOfRightNodeInListedLeft = lastOfRightNodeInListedLeft->right ;
59
+ }
60
+
61
+ n->left = nullptr ;
62
+ n->right = listedLeft;
63
+ lastOfRightNodeInListedLeft->right = listedRight;
64
+
65
+ return n;
66
+ }
67
+
68
+ void flatten (TreeNode *root) {
69
+
70
+ flattenRec (root);
71
+ }
72
+
73
+ }
You can’t perform that action at this time.
0 commit comments