-
-
Notifications
You must be signed in to change notification settings - Fork 605
Expand file tree
/
Copy pathInvertBinaryTree.java
More file actions
36 lines (31 loc) · 815 Bytes
/
InvertBinaryTree.java
File metadata and controls
36 lines (31 loc) · 815 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
package problems.easy;
import problems.utils.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by sherxon on 2016-12-24.
*/
public class InvertBinaryTree {
public TreeNode invertTree(TreeNode root) {
if(root == null)return null;
swap(root);
invertTree(root.left);
invertTree(root.right);
return root;
}
public void swap(TreeNode x){
TreeNode temp=x.left;
x.left=x.right;
x.right=temp;
}
public void invertIterative(TreeNode node){
Queue<TreeNode> q= new LinkedList<>();
q.add(node);
while (!q.isEmpty()){
TreeNode x=q.poll();
swap(x);
if(x.left!=null)q.add(x.left);
if(x.right!=null)q.add(x.right);
}
}
}