LeetCode226: Invert Binary Tree
Nvert a binary tree.
4
/\
2 7
/\/\
1 3 6 9
To
4
/\
7 2
/\/\
9 6 3 1
Trivia:
This problem was too red 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.
Hide Tags Tree
Although I don't know what Homebrew is, but google 90% of people use products that are definitely high, so I guess this trivia is sold as Max Howell.
Solution 1
If the left and right subtree are reversed, you only need to switch the left and right subtree nodes. The inverse rotor tree is the same as the inverse rotor tree, so Recursive Implementation can be used.
Runtime: 4 ms
/** * 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; TreeNode * leftTree=NULL; TreeNode * rightTree=NULL; if(root->left) leftTree=invertTree(root->left); if(root->right) rightTree=invertTree(root->right); root->left=rightTree; root->right=leftTree; return root; }};
Solution 2
This question can also be implemented using non-recursion. The non-recursion implementation code may be a little more, but it is also easy to understand. When a queue is used, the root node is added to the queue at the beginning, and its left and right subnodes are exchanged and the root node is popped up from the queue. If the left and right subnodes are not empty, add the Left and Right subnodes to the queue until there are no elements in the queue. Reference: https://leetcode.com/discuss/40567/my-c-codes-recursive-and-nonrecursive
Runtime: 0 ms
It can be seen from the running time that it makes sense to study non-recursive solutions.
class Solution { public: TreeNode* invertTree(TreeNode* root) { queue
tbpNode; if(root) tbpNode.push(root); TreeNode *curNode, *temp; while(!tbpNode.empty()) { curNode = tbpNode.front(); tbpNode.pop(); temp = curNode->left; curNode->left = curNode->right; curNode->right = temp; if(curNode->left) tbpNode.push(curNode->left); if(curNode->right) tbpNode.push(curNode->right); } return root; } }