62. Construct Binary Search Tree from Pre-order Traversal [중간]
30 Jul 2020 | Daily Algorithms
- Find the left part and right part, then recursively construct the tree.
/**
* 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 {
public:
TreeNode* bstFromPreorder(vector<int>& preorder) {
int i = 0;
return build(preorder, i, INT_MAX);
}
TreeNode* build(vector<int>& A, int& i, int bound)
{
if(i == A.size() || A[i]>bound)
return NULL;
TreeNode* root = new TreeNode(A[i++]);
root->left = build(A, i, root->val);
root->right = build(A, i, bound);
return root;
}
};
- Find the left part and right part, then recursively construct the tree.
/**
* 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 {
public:
TreeNode* bstFromPreorder(vector<int>& preorder) {
int i = 0;
return build(preorder, i, INT_MAX);
}
TreeNode* build(vector<int>& A, int& i, int bound)
{
if(i == A.size() || A[i]>bound)
return NULL;
TreeNode* root = new TreeNode(A[i++]);
root->left = build(A, i, root->val);
root->right = build(A, i, bound);
return root;
}
};
Comments