← Home

897. Increasing Order Search Tree

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
897

Let's make this one less mysterious. For 897. Increasing Order Search Tree, the solution in this repository is mainly a two pointers solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, stack, sliding window.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are increasingBST, inOrder.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Given a 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 1 right child.
03
04Example 1:
05Input: [5,3,6,2,4,null,8,1,null,null,null,7,9]
06
07       5
08      / \
09    3    6
10   / \    \
11  2   4    8
12 /        / \ 
131        7   9
14
15Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
16
17 1
18  \
19   2
20    \
21     3
22      \
23       4
24        \
25         5
26          \
27           6
28            \
29             7
30              \
31               8
32                \
33                 9  
34Note:
35
36The number of nodes in the given tree will be between 1 and 100.
37Each node will have a unique integer value from 0 to 1000.
38**/
39
40//Runtime: 72 ms, faster than 56.90% of C++ online submissions for Increasing Order Search Tree.
41//Memory Usage: 37.7 MB, less than 5.68% of C++ online submissions for Increasing Order Search Tree.
42/**
43 * Definition for a binary tree node.
44 * struct TreeNode {
45 *     int val;
46 *     TreeNode *left;
47 *     TreeNode *right;
48 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
49 * };
50 */
51class Solution {
52public:
53    TreeNode* increasingBST(TreeNode* root) {
54        //in-order traversal
55        stack<TreeNode*> stk;
56        TreeNode* cur = root;
57        TreeNode* newcur = NULL;
58        TreeNode* newroot = NULL;
59        bool isFirst = true;
60        
61        while(cur!=NULL || stk.size() > 0){
62            while(cur!=NULL){
63                stk.push(cur);
64                cur = cur->left;
65            }
66            cur = stk.top();
67            stk.pop();
68            
69            TreeNode node = TreeNode(cur->val);
70            if(isFirst){
71                newroot = new TreeNode(cur->val);
72                newcur = newroot;
73                isFirst = !isFirst;
74            }else{
75                newcur->right = new TreeNode(cur->val);
76                newcur = newcur->right;
77            }
78            
79            cur = cur->right;
80        }
81        
82        return newroot;
83    }
84};
85
86//Approach 1: In-Order Traversal
87//Runtime: 72 ms, faster than 56.90% of C++ online submissions for Increasing Order Search Tree.
88//Memory Usage: 37 MB, less than 18.44% of C++ online submissions for Increasing Order Search Tree.
89/**
90Complexity Analysis
91
92Time Complexity: O(N)O(N), where NN is the number of nodes in the given tree.
93
94Space Complexity: O(N)O(N), the size of the answer. 
95**/
96/**
97 * Definition for a binary tree node.
98 * struct TreeNode {
99 *     int val;
100 *     TreeNode *left;
101 *     TreeNode *right;
102 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
103 * };
104 */
105 
106 /**
107class Solution {
108public:
109    void inOrder(TreeNode* root, vector<int>& values){
110        if(root==NULL) return;
111        inOrder(root->left, values);
112        values.push_back(root->val);
113        inOrder(root->right, values);
114    }
115    
116    TreeNode* increasingBST(TreeNode* root) {
117        vector<int> values;
118        inOrder(root, values);
119        
120        TreeNode* newcur = new TreeNode(0);
121        TreeNode* newroot = newcur;
122        
123        for(auto val : values){
124            newcur->right = new TreeNode(val);
125            newcur = newcur->right;
126        }
127        
128        return newroot->right;
129    }
130};
131**/
132
133/**
134Approach 2: Traversal with Relinking
135Intuition and Algorithm
136
137We can perform the same in-order traversal as in Approach 1. 
138During the traversal, we'll construct the answer on the fly, 
139reusing the nodes of the given tree by cutting their left child and adjoining them to the answer.
140**/
141
142/**
143Time Limit Exceeded
144Last executed input
145[379
146826]
147**/
148
149/**
150class Solution {
151public:
152    TreeNode* newcur;
153    
154    void inOrder(TreeNode* node){
155        if(node==NULL) return;
156        inOrder(node->left);
157        newcur->left = NULL;
158        newcur->right = node;
159        newcur = node;
160        inOrder(node->right);
161    }
162    
163    TreeNode* increasingBST(TreeNode* root) {
164        TreeNode* newroot = new TreeNode(0);
165        newcur = newroot;
166        inOrder(root);
167        return newroot->right;
168    }
169};
170**/

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.