题目
Invert a binary tree.
Example:
Input:
4 / \ 2 7 / \ / \ 1 3 6 9Output:
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 f*** off.
分析
采用深度遍历。
需要注意的是,有可能根结点为NULL值。
源代码
TreeNode* invertTree(TreeNode* root) {
if (root == NULL || (root->left == NULL && root->right == NULL))
return root;
else
{
TreeNode *temp;
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;
}