Skip to content

Commit 1f7dfd3

Browse files
authored
Create 114. Flatten Binary Tree to Linked List
1 parent 1e81d19 commit 1f7dfd3

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Diff for: 114. Flatten Binary Tree to Linked List

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public void flatten(TreeNode root) {
3+
if(root == null) return;
4+
5+
TreeNode tempLeft = root.left;
6+
TreeNode tempRight = root.right;
7+
8+
root.left = null;
9+
10+
flatten(tempLeft);
11+
flatten(tempRight);
12+
13+
root.right = tempLeft;
14+
TreeNode current = root;
15+
while(current.right != null) current = current.right;
16+
current.right = tempRight;
17+
18+
}
19+
}
20+
21+
class Solution {
22+
public void flatten(TreeNode root) {
23+
if(root == null) return;
24+
while(root != null){
25+
if(root.left != null) {
26+
TreeNode left = root.left;
27+
TreeNode current = left;
28+
while(current.right != null) current = current.right;
29+
current.right = root.right; // Morris Traversal main step
30+
root.left =null;
31+
root.right = left;
32+
}
33+
root = root.right;
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)