File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change @@ -20,4 +20,31 @@ public void flatten(TreeNode root) {
20
20
}
21
21
}
22
22
}
23
+
24
+ public static class Solution2 {
25
+
26
+ /**
27
+ * Credit: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/solution/
28
+ */
29
+ public void flatten (TreeNode root ) {
30
+ flat (root );
31
+ }
32
+
33
+ private TreeNode flat (TreeNode curr ) {
34
+ if (curr == null ) {
35
+ return null ;
36
+ }
37
+ if (curr .left == null && curr .right == null ) {
38
+ return curr ;
39
+ }
40
+ TreeNode leftTail = flat (curr .left );
41
+ TreeNode rightTail = flat (curr .right );
42
+ if (leftTail != null ) {
43
+ leftTail .right = curr .right ;
44
+ curr .right = curr .left ;
45
+ curr .left = null ;
46
+ }
47
+ return rightTail == null ? leftTail : rightTail ;
48
+ }
49
+ }
23
50
}
You can’t perform that action at this time.
0 commit comments