-
-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathInvertBinaryTree.java
More file actions
38 lines (29 loc) · 673 Bytes
/
InvertBinaryTree.java
File metadata and controls
38 lines (29 loc) · 673 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
package leetcode;
import util.TreeNode;
import java.util.Deque;
import java.util.LinkedList;
/**
* @author nikoo28 on 9/17/17
*/
class InvertBinaryTree {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
final Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
while (!stack.isEmpty()) {
final TreeNode node = stack.pop();
final TreeNode left = node.left;
node.left = node.right;
node.right = left;
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}
return root;
}
}