您的位置:首页 > 其它

Invert Binary Tree

2015-07-26 11:57 197 查看
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.

Google拒绝Max Howell:百分之90的工程师都用你写的软件,但你不能在白板上转换二叉树,滚蛋吧。

题目很简单,leetcode加这道题是因为Homebrew作者面试谷歌却没写出来被拒了,然后还在推上吐槽。我一开始居然想成了将二叉树对称,怎么想也想不出来。结果就是将二叉树的左右子树交换,递归swap左右子树就好了,代码如下:

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* IBT(TreeNode* root)
{
TreeNode* temp=root->left;
root->left=root->right;
root->right=temp;
invertTree(root->left);
invertTree(root->right);
}
TreeNode* invertTree(TreeNode* root) {
TreeNode* result=root;
if(root==NULL) return NULL;
IBT(root);
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: