Leetcode[226] Invert Binary Tree
28 Nov 2015###Task1 Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9 to
4
/ \
7 2
/ \ / \
9 6 3 1
###Python ####Recursive
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return
root.right, root.left = root.left, root.right
self.invertTree(root.left)
self.invertTree(root.right)
return root
####Iterative
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return None
stack = []
stack.append(root)
while len(stack):
cur = stack.pop()
if cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
cur.left, cur.right = cur.right, cur.left
return root
###Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return root;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
###Points
- We need TEMPERARY VALUE whenver we want to swap values; even left & right subtree
- Iterative: can be done both in DFS and BFS. why? all we need is to traverse the tree.