Invert a binary tree.
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
Do it in recursion is acceptable, can you do it without recursion?
We just traverse the tree and when we reach a tree node, we swap the left node pointer and right node pointer.
We can do this very easy if we use 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 Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void invertBinaryTree(TreeNode root) {
// write your code here
if (root == null) {
return ;
}
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
invertBinaryTree(root.left);
invertBinaryTree(root.right);
}
}
Without recursion, we can use a Stack to simulate the tree's traversal.
/**
* 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) {
Stack<TreeNode> stack = new Stack<TreeNode>();
if (root != null) {
stack.push(root);
while (!stack.empty()) {
TreeNode cur = stack.pop();
TreeNode tmp = cur.left;
cur.left = cur.right;
cur.right = tmp;
if (cur.left != null) {
stack.push(cur.left);
}
if (cur.right != null) {
stack.push(cur.right);
}
}
}
}
}