思路:
递归,递归最主要的就是处理好一般情况。
代码:
/**
* 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* upsideDownBinaryTree(TreeNode* root) {
if(!root || !root->left) return root;
auto l = root->left;
auto r = root->right;
root->left = nullptr;
root->right = nullptr;
auto res = upsideDownBinaryTree(l);
l->left = r;
l->right = root;
return res;
}
};
评论区