-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy path114. Flatten Binary Tree to Linked List
More file actions
43 lines (41 loc) · 1.16 KB
/
114. Flatten Binary Tree to Linked List
File metadata and controls
43 lines (41 loc) · 1.16 KB
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
43
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void flatten(TreeNode root) {
if(root != null){
flattenReturnLast(root);
}
else{
return;
}
}
public TreeNode flattenReturnLast(TreeNode root){
if(root.left != null && root.right != null){
TreeNode returnValue = flattenReturnLast(root.right);
TreeNode leftReturn = flattenReturnLast(root.left);
leftReturn.right = root.right;
root.right = root.left;
root.left = null;
return returnValue;
}
else if(root.left == null && root.right != null){
return flattenReturnLast(root.right);
}
else if(root.left != null && root.right == null){
TreeNode returnValue = flattenReturnLast(root.left);
root.right = root.left;
root.left = null;
return returnValue;
}
else{//both are null
return root;
}
}
}