Skip to content

Files

Latest commit

Dec 3, 2020
04bd579 · Dec 3, 2020

History

History
This branch is 2352 commits behind lzl124631x/LeetCode:master.

897. Increasing Order Search Tree

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Dec 3, 2020

Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.

 

Example 1:

Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]

Example 2:

Input: root = [5,1,7]
Output: [1,null,5,null,7]

 

Constraints:

  • The number of nodes in the given tree will be in the range [1, 100].
  • 0 <= Node.val <= 1000

Related Topics:
Tree, Depth-first Search, Recursion

Solution 1. In-order Traversal

// OJ: https://leetcode.com/problems/increasing-order-search-tree
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(H)
class Solution {
private:
    TreeNode *prev;
    void inorder(TreeNode *root) {
        if (!root) return;
        inorder(root->left);
        root->left = NULL;
        prev->right = root;
        prev = root; 
        inorder(root->right);
    }
public:
    TreeNode* increasingBST(TreeNode* root) {
        TreeNode head;
        prev = &head;
        inorder(root);
        return head.right;
    }
};

Solution 2. Post-order Traversal

// OJ: https://leetcode.com/problems/increasing-order-search-tree/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(H)
class Solution {
    pair<TreeNode*, TreeNode*> dfs(TreeNode* root) {
        TreeNode *head = root, *tail = root;
        if (root->left) {
            auto [leftHead, leftTail] = dfs(root->left);
            head = leftHead;
            leftTail->right = root;
            root->left = NULL;
        }
        if (root->right) {
            auto [rightHead, rightTail] = dfs(root->right);
            root->right = rightHead;
            tail = rightTail;
        }
        return { head, tail };
    }
public:
    TreeNode* increasingBST(TreeNode* root) {
        return dfs(root).first;
    }
};