Invert Binary Tree
LeetCode: Invert Binary Tree
Problem:
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
- Trivial:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
- Analysis:
Invert every node recursively.
- Code - Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
invertTree(root.left);
invertTree(root.right);
TreeNode node = root.left;
root.left = root.right;;
root.right = node;
return root;
}
}
- Code - C++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == NULL) {
return NULL;
}
invertTree(root->left);
invertTree(root->right);
TreeNode* node = root->left;
root->left = root->right;;
root->right = node;
return root;
}
};
- Code - Python:
# 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 root == None:
return None
self.invertTree(root.left)
self.invertTree(root.right)
node = root.left
root.left = root.right
root.right = node
return root
- Code - C:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* invertTree(struct TreeNode* root) {
if (root == 0) {
return 0;
}
invertTree(root->left);
invertTree(root->right);
struct TreeNode* node = root->left;
root->left = root->right;;
root->right = node;
return root;
}
- Time Complexity: O(N), N is the number of nodes.
- Space Complexity: in-memory