forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path114_flatten.java
35 lines (32 loc) · 832 Bytes
/
114_flatten.java
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
if(root!=null){
root = flattenRoot(root);
}
}
public TreeNode flattenRoot(TreeNode root){
TreeNode last = root;
TreeNode left = root.left;
TreeNode right = root.right;
root.left = null;
root.right = null; // Copy two object to other places and reset root
if(left!=null){
last.right = left;
last = flattenRoot(left);
}
if(right!=null){
last.right = right;
last = flattenRoot(right);
}
return last;
}
}