思路:
刚开始的想法是二叉树层序遍历记录每一层,用一个二维数组存下来,反转每一层之后然后再遍历一次,依次赋值,O(n)。
然后发现递归一下好像也可以,算法O(logn)
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return root;
auto p = root;
Reverse(root);
return p;
}
void Reverse(TreeNode* root){
if(!root) return;
if(root->left) Reverse(root->left);
if(root->right) Reverse(root->right);
auto tmp = root->left;
root->left = root->right;
root->right = tmp;
}
};
评论区