226. Invert Binary Tree
226. Invert Binary Tree
1. 问题
Invert a binary tree.
Example:
input:
4
/ \
2 7
/ \ / \
1 3 6 9
output:
4
/ \
7 2
/ \ / \
9 6 3 1
轶事:牛逼的工程师都这样吗???
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.
2. 解法
- 思路:通过递归实现将左右子树翻转。
- C代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/*递归将左右子树交换,从而完成整棵树的翻转*/
struct TreeNode* invertTree(struct TreeNode* root){
if(NULL == root){
return NULL;
}
struct TreeNode* tmp = root->right;
root->right = root->left;
root->left = tmp;
invertTree(root->left);
invertTree(root->right);
return root;
}

浙公网安备 33010602011771号