Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1最先想到的当然是递归的思想,将两个左右指针进行互换:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* invertTree(struct TreeNode* root) {
if (!root)
return NULL;
root->left = invertTree(root->left);
root->right = invertTree(root->right);
struct TreeNode *tmp = root->left;
root->left = root->right;
root->right = tmp;
return root;
}