题目:
Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9
to
4 / \ 7 2 / \ / \ 9 6 3 1
翻译:
翻转一颗二叉树。
4 / \ 2 7 / \ / \ 1 3 6 9
到
4 / \ 7 2 / \ / \ 9 6 3 1
思路:
很容易想到使用递归,但是要注意边界条件。
C++代码(Visual Studio 2017):
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == NULL)
return NULL;
if (root->left == NULL && root->right == NULL)
return root;
TreeNode* temp;
TreeNode* right = invertTree(root->right);
TreeNode* left = invertTree(root->left);
temp = left;
root->left = right;
root->right = temp;
return root;
}
};