[LeetCode] Increasing Order Search Tree

897. Increasing Order Search Tree

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
vector<TreeNode*> A;
void helper(TreeNode* node) {
if(!node) return;
helper(node->left);
A.push_back(node);
helper(node->right);
}
public:
TreeNode* increasingBST(TreeNode* root) {
if(!root) return root;
helper(root);
for(int i = 0; i < A.size() - 1; i++) {
A[i]->left = nullptr;
A[i]->right = A[i+1];
}
A.back()->left = nullptr;
return A[0];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/17/PS/LeetCode/increasing-order-search-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.