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.
我的笨方法:DFS
/**
* 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* p_left=invertTree(root->left);
TreeNode* p_right=invertTree(root->right);
root->left=p_right;
root->right=p_left;
return root;
}
};
改进DFS
/**
* 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) {
invertTree(root->left);
invertTree(root->right);
std::swap(root->left, root->right);
}
return root;
}
};
利用栈或队列的BFS
/**
* 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) {
std::stack<TreeNode*> stk;
stk.push(root);
while (!stk.empty()) {
TreeNode* p = stk.top();
stk.pop();
if (p) {
stk.push(p->left);
stk.push(p->right);
std::swap(p->left, p->right);
}
}
return root;
}
};
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;
}