-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlattenBT.java
More file actions
42 lines (38 loc) · 980 Bytes
/
FlattenBT.java
File metadata and controls
42 lines (38 loc) · 980 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class FlatterBT {
public void flatten(TreeNode root) {
helper(root);
}
TreeNode helper(TreeNode curr){
if(curr == null)
return null;
TreeNode tail1 = helper(curr.left);
TreeNode tail2 = helper(curr.right);
TreeNode temp = curr.right;
curr.right = curr.left;
curr.left = null;
tail1 = tail1==null? curr : tail1;
tail1.right = temp;
return tail2==null? tail1 : tail2;
}
/*
public void flatten(TreeNode root) {
if(root == null) return;
TreeNode right = root.right;
root.right = root.left;
root.left = null;
TreeNode ptr = root;
while(ptr.right != null) ptr = ptr.right;
ptr.right = right;
flatten(root.right);
}
*/
}