Created
March 10, 2019 04:19
-
-
Save lctseng/5976b94d8f997ebba501146ebc0597af to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
TreeNode* bstFromPreorder(vector<int>& preorder, int& index, int parentIndex) { | |
if(index >= preorder.size() || (parentIndex >= 0 && preorder[index] >= preorder[parentIndex])){ | |
return nullptr; | |
} | |
else{ | |
TreeNode* root = new TreeNode(preorder[index]); | |
int thisIndex = index; | |
index++; | |
root->left = bstFromPreorder(preorder, index, thisIndex); | |
root->right = bstFromPreorder(preorder, index, parentIndex); | |
return root; | |
} | |
} | |
TreeNode* bstFromPreorder(vector<int>& preorder) { | |
int index = 0; | |
return bstFromPreorder(preorder, index, -1); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment