Invert a binary tree.
4 / 2 7 / / 1 3 6 9
to
4 / 7 2 / / 9 6 3 1
Trivia:
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.
Analyse: the same as Binary Tree Level Order Traversal except that we need to swap the left and right subtrees of the current node.
1. Recursion: First swap the left and right subtree of the roots, then recursively swap the left and right subtrees of them...
Runtime: 0ms.
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* invertTree(TreeNode* root) { 13 if(!root) return NULL; 14 15 TreeNode* leftSub = root->left; //swap the left and right subtree of the root 16 root->left = root->right; 17 root->right = leftSub; 18 invertTree(root->left); 19 invertTree(root->right); 20 21 return root; 22 } 23 };
2. Iteration: swap the left and right subtree of the current node and push the new left and right subtree into a queue.
Runtime: 0ms.
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* invertTree(TreeNode* root) { 13 if(!root) return NULL; 14 15 queue<TreeNode* > qu; 16 qu.push(root); 17 while(!qu.empty()){ 18 int n = qu.size(); 19 while(n--){ 20 TreeNode* temp = qu.front(); 21 qu.pop(); 22 TreeNode* tempLeft = temp->left; //swap the left and right subtree of the current root 23 temp->left = temp->right; 24 temp->right = tempLeft; 25 26 if(temp->left) qu.push(temp->left); //push the original right subtree of the root first 27 if(temp->right) qu.push(temp->right); //continuously do the process until all nodes are visited 28 } 29 } 30 return root; 31 } 32 };