File tree Expand file tree Collapse file tree 1 file changed +80
-0
lines changed
Expand file tree Collapse file tree 1 file changed +80
-0
lines changed Original file line number Diff line number Diff line change 1+ # 114. Flatten Binary Tree to Linked List
2+
3+ - Difficulty: Medium.
4+ - Related Topics: Tree, Depth-first Search.
5+ - Similar Questions: .
6+
7+ ## Problem
8+
9+ Given a binary tree, flatten it to a linked list in-place.
10+
11+ For example, given the following tree:
12+
13+ ```
14+ 1
15+ / \
16+ 2 5
17+ / \ \
18+ 3 4 6
19+ ```
20+
21+ The flattened tree should look like:
22+
23+ ```
24+ 1
25+ \
26+ 2
27+ \
28+ 3
29+ \
30+ 4
31+ \
32+ 5
33+ \
34+ 6
35+ ```
36+
37+
38+ ## Solution
39+
40+ ``` javascript
41+ /**
42+ * Definition for a binary tree node.
43+ * function TreeNode(val) {
44+ * this.val = val;
45+ * this.left = this.right = null;
46+ * }
47+ */
48+ /**
49+ * @param {TreeNode} root
50+ * @return {void} Do not return anything, modify root in-place instead.
51+ */
52+ var flatten = function (root ) {
53+ helper (root);
54+ };
55+
56+ var helper = function (root ) {
57+ if (! root) return null ;
58+
59+ var leftLast = helper (root .left );
60+ var rightLast = helper (root .right );
61+
62+ if (root .left ) {
63+ leftLast .right = root .right ;
64+ root .right = root .left ;
65+ }
66+
67+ root .left = null ;
68+
69+ return rightLast || leftLast || root;
70+ };
71+ ```
72+
73+ ** Explain:**
74+
75+ nope.
76+
77+ ** Complexity:**
78+
79+ * Time complexity : O(n).
80+ * Space complexity : O(1).
You can’t perform that action at this time.
0 commit comments