Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1Trivia:
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.
解答:
哈哈哈哈哈,太萌了这个题。。。
/**
* 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) return nullptr;
TreeNode* tmp;
tmp=root->left;
root->left=root->right;
root->right=tmp;
invertTree(root->left);
invertTree(root->right);
return root;
}
};
上面的代码还是很有意思的。。。有返回值,但是却没有赋值。。充分利用了递归。
更优雅的解法是这样:
TreeNode* invertTree(TreeNode* root) {
TreeNode* temp;
if(root==NULL) return root;
temp=root->left;
root->left=invertTree(root->right);
root->right=invertTree(temp);
return root;
}
另一个人的BFS,也很简单:
TreeNode* invertTree(TreeNode* root) {
if(nullptr == root) return root;
queue<TreeNode*> myQueue; // our queue to do BFS
myQueue.push(root); // push very first item - root
while(!myQueue.empty()){ // run until there are nodes in the queue
TreeNode *node = myQueue.front(); // get element from queue
myQueue.pop(); // remove element from queue
if(node->left != nullptr){ // add left kid to the queue if it exists
myQueue.push(node->left);
}
if(node->right != nullptr){ // add right kid
myQueue.push(node->right);
}
// invert left and right pointers
TreeNode* tmp = node->left;
node->left = node->right;
node->right = tmp;
}
return root;
}