zoukankan      html  css  js  c++  java
  • Leetcode_897. Increasing Order Search Tree

    题目:https://leetcode.com/problems/increasing-order-search-tree/

    题意:

    将一棵二叉搜索树,重排为一棵递增的二叉排序树。

    解法1:

    rson->root->left的顺序依次遍历整棵树,途中使用头插法建立链表(递增的二叉搜索树)。

    这样做会带来额外的内存开销。

    class Solution
    {
    public:
        TreeNode* result=NULL;
        TreeNode* increasingBST(TreeNode* root)
        {
    
            reverse_postorder(root);
            return result;
        }
    
        void reverse_postorder(TreeNode* root)
        {
            if(root==nullptr)
                return;
            reverse_postorder(root->right);
            TreeNode* node=new TreeNode(root->val);
            node->right=result;
            result=node;
            reverse_postorder(root->left);
        }
    };

    解法2:

    先序遍历树,途中调整指针的指向。

    successor:以当前root为根节点的子树,在整棵树的先序表示中的后继。

    在先序表示中,

    任意节点(node),是以该节点左孩子(node->left)为根节点的子树的后继;

    任意节点(node)的父节点,是以该节点的右孩子(node->right)为根节点的子树的后继;

    class Solution
    {
    public:
        TreeNode* increasingBST(TreeNode* root, TreeNode* successor=nullptr)
        {
            if(root==nullptr)
                return successor;
            TreeNode* res=increasingBST(root->left, root);
            root->left=nullptr;
            root->right=increasingBST(root->right, successor);
            return res;
        }
    };
  • 相关阅读:
    UVA1599 理想路径 Ideal Path(最短路径)
    换根DP
    小w的魔术扑克(树状数组+并查集)
    NOIP 2016蚯蚓(优先队列)
    ZR 动物园
    T105017 seq(DP)
    noip2017酱油记
    noip2017酱油记前篇
    P1985 翻转棋
    luogu P2512 [HAOI2008]糖果传递
  • 原文地址:https://www.cnblogs.com/jasonlixuetao/p/11158251.html
Copyright © 2011-2022 走看看