首页 > 代码库 > [leetcode]Binary Tree Upside Down

[leetcode]Binary Tree Upside Down

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

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

注意要把以前的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;};

 

[leetcode]Binary Tree Upside Down