-->

Saturday, March 11, 2017

[LeetCode] 536. Construct Binary Tree from String

https://leetcode.com/contest/leetcode-weekly-contest-23/problems/construct-binary-tree-from-string/

Solution:
The basic idea is to form the root first; then form the left children; then the right one. So we will use recursion strategy. See code below:

Note: The description for this question is not very clear, for example: the meaning of the '-' (it means negative number actually), and also the number can be larger than 10...

Code:
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8.  * };
  9.  */
  10. class Solution {
  11. public:
  12.     TreeNode* str2tree(string s) {
  13.         TreeNode* res;
  14.         int n = s.size(), i = 0;
  15.         if(n==0) return NULL;
  16.         int flag = 1;
  17.         if(s[i] == '-'){
  18.             flag = -1;
  19.             ++i;
  20.         }
  21.         if(i<n&&(s[i]-'0'>=0)&&(s[i]-'0'<=9)) {
  22.             int t=0;
  23.             while(i<n&&(s[i]-'0'>=0)&&(s[i]-'0'<=9)) t = t*10 + (s[i++]-'0');
  24.             res = new TreeNode(flag*t);
  25.         }
  26.         if(i<n&&s[i]=='('){
  27.             int t = 1, ct = i+1;
  28.             while(t>0&&ct<n){
  29.                 if(s[ct]=='(') ++t;
  30.                 if(s[ct]==')') --t;
  31.                 ++ct;
  32.             }
  33.             if(t==0)res->left = str2tree(s.substr(i+1, ct-i-1)); //left children;
  34.             if(t==0&&ct<n&&s[ct]=='(')res->right = str2tree(s.substr(ct+1, n-ct-2));//right children;
  35.         }
  36.         return res;
  37.     }
  38. };

No comments :

Post a Comment