226 - Invert Binary Tree
Written on October 21, 2015
Tweet
Invert a binary tree
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;
root.left = root.right;
root.right = temp;
invertBinaryTree(root.left);
invertBinaryTree(root.right);
}
}
public class Solution {
public void invertBinaryTree(TreeNode root) {
// write your code here
if (root == null) return;
Stack<treenode> stack = new Stack<treenode>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode curr = stack.pop();
TreeNode temp = curr.left;
curr.left = curr.right;
curr.right = temp;
if (curr.left != null) stack.push(curr.left);
if (curr.right != null) stack.push(curr.right);
}
}
}
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root is None:
return
stack = [root]
while stack:
curr = stack.pop()
curr.left, curr.right = curr.right, curr.left
if curr.left:
stack.append(curr.left)
if curr.right:
stack.append(curr.right)
return root
class Solution(object):
def invertTree(self, root):
if root is None:
return
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root