-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathInvertBinaryTree.java
62 lines (56 loc) · 1.54 KB
/
InvertBinaryTree.java
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
*Easy Invert Binary Tree Show result
Invert a binary tree.
Example
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
Challenge
Do it in recursion is acceptable, can you do it without recursion?
*/
/**
* 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 InvertBinaryTree {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void invertBinaryTree(TreeNode root) {
if (root != null) {
TreeNode left = root.left;
invertBinaryTree(left);
TreeNode right = root.right;
invertBinaryTree(right);
root.left = right;
root.right = left;
}
}
/*******************************************************************/
public void invertBinaryTree(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = root;
while (!stack.isEmpty() || cur != null) {
if (cur != null) {
stack.push(cur);
cur = cur.left;
} else {
TreeNode node = stack.pop();
TreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
cur = node.left;
}
}
}
}