Invert Binary Tree
题目
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.
解析
题目需要我们做的就是将每个节点的左右子节点相互调换,包括节点的值以及相应的左右节点。二叉树的题目我们一般可以用递归和非递归的方法来解决。
1. 递归解决
/**
* 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 root;
} else {
TreeNode * temp = root->left;
root->left = root->right;
root->right = temp;
if (root->left != NULL) {
invertTree(root->left);
}
if (root->right != NULL) {
invertTree(root->right);
}
return root;
}
}
};
2. 非递归解决
/**
* 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) {
queue<TreeNode*> tree;
tree.push(root);
while (!tree.empty()) {
TreeNode* temp = tree.front();
tree.pop();
if (temp == NULL) continue;
swap(temp->left, temp->right);
if (temp->left != NULL) tree.push(temp->left);
if (temp->right != NULL) tree.push(temp->right);
}
return root;
}
};