How to convert a binary tree to binary search tree in-place, i.e., we cannot use any extra space

前端 未结 11 1116
借酒劲吻你
借酒劲吻你 2021-01-31 22:12

How to convert a binary tree to binary search tree in-place, i.e., we cannot use any extra space.

11条回答
  •  执念已碎
    2021-01-31 22:38

    struct Node
    {
        int value;
        Node* left;
        Node* right;
    };
    
    void swap(int& l, int& r)
    {
        int t = l;
        l = r;
        r = t;
    }
    
    void ConvertToBST(Node* n, Node** max)
    {
        if (!n) return;
    
        // leaf node
        if (!n->left && !n->right)
        {
            *max = n;
            return;
        }
    
        Node *lmax = NULL, *rmax = NULL;
        ConvertToBST(n->left, &lmax);
        ConvertToBST(n->right, &rmax);
    
        bool swapped = false;
        if (lmax && n->value < lmax->value)
        {
            swap(n->value, lmax->value);
            swapped = true;
        }
    
        if (rmax && n->value > rmax->value)
        {
            swap(n->value, n->right->value);
            swapped = true;
        }
    
        *max = n;
        if (rmax && rmax->value > n->value) *max = rmax;
    
        // If either the left subtree or the right subtree has changed, convert the tree to BST again
        if (swapped) ConvertToBST(n, max);
    }
    

提交回复
热议问题