1957

无聊蛋疼的1957写的低端博客
随笔 - 214, 文章 - 1, 评论 - 38, 阅读 - 21万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

[leetcode]Binary Tree Upside Down

Posted on   1957  阅读(824)  评论(1编辑  收藏  举报

= =买了书才能做的题。。。

就是按说明来搞就行了,没啥算法。。。

注意要把以前的left,right设置为nullptr,不然就是有环了,代码中加黑部分。

 

复制代码
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* rotate(TreeNode* root) {
        if (root == nullptr || root->left == nullptr) {
            ans = root;
            return root;
        }
        TreeNode* tree = rotate(root->left);
        tree->right = root;
        tree->left = root->right;
        root->left = nullptr;
        root->right = nullptr;
        return tree->right;
    }
    
    TreeNode *upsideDownBinaryTree(TreeNode *root) {
        ans = nullptr;
        rotate(root);
        return ans;
    }
private:
    TreeNode* ans;
};
复制代码

 

点击右上角即可分享
微信分享提示