-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbinaryTreeUpsideDown.java
More file actions
40 lines (39 loc) · 1.3 KB
/
binaryTreeUpsideDown.java
File metadata and controls
40 lines (39 loc) · 1.3 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
public class binaryTreeUpsideDown {
/*
思路跟reverse linked list非常像!
也是有recursive 和 iterative的方法
* */
// method 1: recursive
public TreeNode upsideDownBinaryTree(TreeNode root) {
if(root == null) return null;
if(root.left == null) return root;
TreeNode newRoot = upsideDownBinaryTree(root.left);
// do something: change edges
root.left.left = root.right;
root.left.right = root;
root.left = null;
root.right = null;
return newRoot;
}
// method 2: iterative 的方法
public TreeNode upsideDownBinaryTree2(TreeNode root) {
TreeNode cur = root;
TreeNode left = null;
TreeNode right = null;
while(cur != null){
// store nodes which will be used next iteration before any changes
// because if we change any node, those nodes can't be access
TreeNode next = cur.left;
TreeNode nextRight = cur;
TreeNode nextLeft = cur.right;
// change edges
cur.left = left;
cur.right = right;
// update nodes using information we stored at first
cur = next;
left = nextLeft;
right = nextRight;
}
return right;
}
}