226. Invert Binary Tree
题目描述:
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.
题目思路:
上面的max howell碰见的事有点意思,特意搜了搜。
这个题让交换左右子数,存一个变量temp,用来交换就ok
时间复杂度O(n)
答案详解:
/**
* 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:
void convert(TreeNode* root)
{
if(root)
{
struct TreeNode* p =root;
p = root->left;
root->left = root->right;
root->right = p;
convert(root->left);
convert(root->right);
}
}
TreeNode* invertTree(TreeNode* root) {
if(root==NULL)
return NULL;
convert(root);
return root;
}
};
还没有评论,来说两句吧...