[InterviewBit] Inorder Traversal of Cartesian Tree

Inorder Traversal of Cartesian Tree

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
TreeNode* helper(vector<int>& A, int l, int r) {
if(l > r) return NULL;
if(l == r) return new TreeNode(A[l]);
int ma = max_element(begin(A) + l, begin(A) + r + 1) - begin(A);
TreeNode* res = new TreeNode(A[ma]);
res->left = helper(A,l,ma - 1);
res->right = helper(A,ma + 1,r);
return res;
}
TreeNode* Solution::buildTree(vector<int> &A) {
return helper(A, 0, A.size() - 1);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/03/PS/interviewbit/inorder-traversal-of-cartesian-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.