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.
思路:递归,交换左右子树的指针,不断递归交换直到叶子节点
void swapChildNode(struct TreeNode* fatherNode)
{
struct TreeNode* temp = fatherNode->left;
fatherNode->left = fatherNode->right;
fatherNode->right = temp;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* invertTree(struct TreeNode* root)
{
if(root == NULL)
{
return NULL;
}
swapChildNode(root);
invertTree(root->left);
invertTree(root->right);
return root;
}