homebrew的作者面试google,面试官要求他手写一个反转一个二叉树的功能。最后却没写出来,于是有了下面的新闻:
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.
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 == NULL)
return ;
if(root->left == NULL && root->right == NULL)
return root;
struct TreeNode* temp;
temp=root->left;
root->left = root->right;
root->right = temp;
if(root->left)
invertTree(root->left);
if(root->right)
invertTree(root->right);
return root;
}