leetcode Revert Binary Tree
2016-08-02 17:38
162 查看
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.
to
这个题我在书上看到过,我认为上面的图解比较清楚,就放了上来。
大体思路:一层一层反转左右节点,直到下到叶子
/**
* 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;
}
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 9
to
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;
}
相关文章推荐
- LeetCode-Convert Sorted List to Binary Search Tree
- LeetCode Balanced Binary Tree
- LeetCode 114 Flatten Binary Tree to Linked List
- leetcode 104--Maximum Depth of Binary Tree
- leetcode maximum-depth-of-binary-tree
- leetcode Binary Tree Level Order Traversal II
- leetcode[145]:Binary Tree Postorder Traversal
- [Leetcode]110. Balanced Binary Tree
- LeetCode Maximum Binary Tree
- LeetCode: Flatten Binary Tree to Linked List
- [LeetCode] Binary Tree Inorder Traversal Solution
- LeetCode 236. Lowest Common Ancestor of a Binary Tree
- LeetCode - Binary Tree Level Order Traversal
- leetcode 108. Convert Sorted Array to Binary Search Tree-数组转搜索树|递归|非递归
- LeetCode 之 Balanced Binary Tree
- LeetCode: Balanced Binary Tree
- Leetcode_114_Flatten Binary Tree to Linked List
- LeetCode – Refresh – Binary Tree Level Order Traversal ii
- [LeetCode]Binary Tree Level Order Traversal
- 【平衡二叉树】leetcode 110. Balanced Binary Tree