题目:
Invert a binary tree.
Example:
Input:
4 / \ 2 7 / \ / \ 1 3 6 9
Output:
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 f*** off.
代码:
/**
* 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* invertTree(TreeNode* root) {
if(root == NULL)
return NULL;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
TreeNode* cur_node = q.front();
q.pop();
if(cur_node->left)
q.push(cur_node->left);
if(cur_node->right)
q.push(cur_node->right);
TreeNode* tmp = cur_node->right;
cur_node->right = cur_node->left;
cur_node->left = tmp;
}
return root;
}
};
这篇博客介绍了一个编程问题——翻转二叉树,它源于Max Howell的一条推特,该推特揭示了谷歌面试中对于技术实际应用的重视。提供的代码实现了一个使用广度优先搜索来翻转二叉树的算法。
303

被折叠的 条评论
为什么被折叠?



