-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinary_156.java
More file actions
40 lines (33 loc) · 963 Bytes
/
Binary_156.java
File metadata and controls
40 lines (33 loc) · 963 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
class Binary_156 {
// Most voted solution: Recursive
public TreeNode upsideDownBinaryTree(TreeNode root) {
if (root == null || root.left == null) {
return root;
}
TreeNode newRoot = upsideDownBinaryTree(root.left);
root.left.left = root.right; // node 2 left children
root.left.right = root; // node 2 right children
root.left = null;
root.right = null;
return newRoot;
}
// Most voted solution: Iterative
/*
public TreeNode upsideDownBinaryTree(TreeNode root) {
TreeNode curr = root;
TreeNode next = null;
TreeNode temp = null;
TreeNode prev = null;
while(curr != null) {
next = curr.left;
// swapping nodes now, need temp to keep the previous right child
curr.left = temp;
temp = curr.right;
curr.right = prev;
prev = curr;
curr = next;
}
return prev;
}
*/
}