226. Invert Binary Tree

古城微笑少年丶 2022-06-08 14:19 260阅读 0赞

题目描述:

Invert a binary tree.

  1. 4
  2. / \
  3. 2 7
  4. / \ / \
  5. 1 3 6 9

to

  1. 4
  2. / \
  3. 7 2
  4. / \ / \
  5. 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;
}
};

发表评论

表情:
评论列表 (有 0 条评论,260人围观)

还没有评论,来说两句吧...

相关阅读