Skip to content
This repository has been archived by the owner on Nov 14, 2022. It is now read-only.

cpp files #750

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions inorderTraversel.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include<bits/stdc++.h>
using namespace std;

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

TreeNode * buildTreeRec(int s,int e,vector<int> inorderTraversel ){
if(s>e){
return NULL;
}

int ind = -1;
int max = INT_MIN;
for(int i=s;i<=e;i++){
if(inorderTraversel[i]>max){
max = inorderTraversel[i];
ind = i;
}
}
TreeNode *curr = new TreeNode(inorderTraversel[ind]);

curr->left = buildTreeRec(s,ind-1,inorderTraversel);
curr->right = buildTreeRec(ind+1,e,inorderTraversel);
return curr;

}
TreeNode* Solution::buildTree(vector<int> &A) {
return buildTreeRec(0,A.size()-1,A);

}
31 changes: 31 additions & 0 deletions sortedArrayToBST.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include<bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};


TreeNode *bstFromSortedVector(const vector<int> &A,int s, int e){
if(s>e){
return (NULL);
}

int mid = (s+e)/2;
TreeNode *root = new TreeNode(A[mid]);
root->left = bstFromSortedVector(A,s,mid-1);
root->right = bstFromSortedVector(A,mid+1,e);

return (root);



}
TreeNode *sortedArrayToBST(const vector<int> &A) {

TreeNode *root = bstFromSortedVector(A,0,A.size()-1);
return (root);

}