536. Construct Binary Tree from String

17 篇文章 0 订阅
16 篇文章 0 订阅

You need to construct a binary tree from a string consisting of parenthesis and integers.

The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root’s value and a pair of parenthesis contains a child binary tree with the same structure.

You always start to construct the left child node of the parent first if it exists.

Example:
Input: “4(2(3)(1))(6(5))”
Output: return the tree root node representing the following tree:

   4
 /   \
2     6

/ \ /
3 1 5
Note:
There will only be ‘(‘, ‘)’, ‘-’ and ‘0’ ~ ‘9’ in the input string.

对于例题中的”4(2(3)(1))(6(5))”,可知4是根节点,“2(3)(1)”是左子树,“6(5)”是右子树。可以想到应该用递归的方式建树。
这里怎么判断它的左子树的开始和结尾呢?
通过对”()”进行计数,当遇到’(‘加1,遇到‘)’减去1。当为0时,说明括号是完全匹配的,此时它自己可以形成一个新树。剩下的就是加括号的右子树的字符串。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* str2tree(string s) {
        if(s.size()==0) return NULL;
       int val=0;int i=0,j,n=s.size();
       int sign=1;
       if(s[0]=='-') {sign=-1;i++;}
       while(i<n && s[i]!='(') {val=val*10+(s[i]-'0');i++;}//此时,s[i]是'('
       TreeNode* root=new TreeNode(val*sign);
       if(i==n) return root;//如果没有孩子
       int num=1;j=i;
       while(num!=0)
       {
           j++;
          if(s[j]=='(') num++;
          else if(s[j]==')') num--;
       }//找到右子树结尾的括号')'

        root->left=str2tree(s.substr(i+1,j-i-1));
        if(j+2<n)//判断有没有右子树
        root->right=str2tree(s.substr(j+2,n-3-j));
       return root;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值