码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Binary Tree Upside Down"

时间:2015-08-20 14:44:10      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

Recursion, a natural thought:

技术分享
class Solution 
{
    //    Top : BottomRight
    std::pair<TreeNode *, TreeNode *> rotate(TreeNode *p)
    {
        if (!p->left && !p->right)
        {
            return make_pair(p, p);
        }

        auto r = rotate(p->left);
        r.second->left = p->right;
        r.second->right = p;
        
        if (p->right)
            p->right->left = p->right->right = nullptr;
        p->left = p->right = nullptr;
        
        return make_pair(r.first, p);
    }
public:
    TreeNode* upsideDownBinaryTree(TreeNode* root) 
    {
        if (!root) return root;
        auto r = rotate(root);
        return r.first;
    }
};
View Code

Iterative, just picture it in your mind :)

技术分享
class Solution 
{
public:
    TreeNode* upsideDownBinaryTree(TreeNode* root) 
    {
        TreeNode *cur = root, *p = nullptr, *pr = nullptr;
        while(cur)
        {
            // Rotate
            auto left = cur->left; // store
            cur->left = pr;
            pr = cur->right; // move on
            cur->right= p;
            
            // Move on left-wards
            p = cur;
            cur = left;
        }
        return p;
    }
};
View Code

LeetCode "Binary Tree Upside Down"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4744892.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!