-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path0175. Invert Binary Tree.java
More file actions
43 lines (41 loc) · 1.14 KB
/
0175. Invert Binary Tree.java
File metadata and controls
43 lines (41 loc) · 1.14 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 of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void invertBinaryTree(TreeNode root) {
if(root == null) return;
TreeNode temp = root.left; //swapping left for right
root.left = root.right;
root.right = temp;
invertBinaryTree(root.left);
invertBinaryTree(root.right);
}
public void noRecursion(TreeNode root) {
Stack<TreeNode> toVisit = new Stack<>();
toVisit.push(root);
while(toVisit.isEmpty() != true){
TreeNode curr = toVisit.pop();
TreeNode temp = curr.left;
curr.left = curr.right;
curr.right = temp;
if(curr.left != null){
toVisit.push(curr.left);
}
if(curr.right != null){
toVisit.push(curr.right);
}
}
}
}