G2A Many GEOs
SHARE
TWEET

Construct Binary Search Tree from Preorder Traversal

a guest Apr 8th, 2020 97 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     struct TreeNode *left;
  6.  *     struct TreeNode *right;
  7.  * };
  8.  */
  9.  
  10. struct TreeNode* createNode(int n){
  11.     struct TreeNode* node = malloc(sizeof(struct TreeNode));
  12.     node->val = n;
  13.     node->left = node->right = NULL;
  14.     return node;
  15. }
  16.  
  17. struct TreeNode* insert(struct TreeNode* root, int n){
  18.     if(!root)
  19.         return createNode(n);
  20.     if(root->val > n)
  21.         root->left = insert(root->left, n);
  22.     else
  23.         root->right = insert(root->right, n);
  24.     return root;
  25. }
  26.  
  27. struct TreeNode* bstFromPreorder(int* preorder, int preorderSize){
  28.     struct TreeNode* root = NULL;
  29.     for(int i = 0; i < preorderSize; i++)
  30.         root = insert(root, preorder[i]);
  31.    
  32.     return root;
  33. }
RAW Paste Data
Ledger Nano X - The secure hardware wallet
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top