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 f*** off.Invert a binary tree.
Example:Input:
4 / \ 2 7 / \ / \ 1 3 6 9Output:
4 / \ 7 2 / \ / \ 9 6 3 1
This is easy! I meant easy. Most tree-related algorithms such as traversal can be done using recursion, which is a straightforward approach.
/**
* 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; // terminal condition
}
auto left = invertTree(root->left); // invert left sub-tree
auto right = invertTree(root->right); // invert right sub-tree
root->left = right; // put right on left
root->right = left; // put left on right
return root;
}
};
We need to recursively invert left and right sub-trees until they are NULL. Then we just need to swap the left and right sub-trees.
BTW, the ‘auto’ keyword in C++ is similar to the ‘var’ keyword in C#, which allows the compiler determine the best data-types for you.
See also other posts on inverting the binary tree:
- Teaching Kids Programming – Recursive Algorithm to Invert a Binary Tree
- How to Invert a Binary Tree in C/C++?
- Invert a Binary Tree using GoLang
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: C++ Coding Exercise - Self Crossing
Next Post: How to Delete Node in a Linked List (Given Only Access to That Node)?