Construct Binary Tree from String

53 篇文章 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:

  1. There will only be '('')''-' and '0' ~ '9' in the input string.
  2. An empty tree is represented by "" instead of "()".

思路:这题可以跟 Brace Expansion联合起来一起看,都是递归循环,找到中间括号的内容,然后做dfs;

注意,这题实际上是要把左括号和右括号给去掉的,也就是内部循环的时候,其实找到左边界和右边界之后,还是把左边和右边的括号给去掉了,刚开始为什么不去掉,因为刚开始进来的时候是有root的,但是如果循环右边的时候,一定要把左右两个括号给去掉。否则,找到左括号之后,会出现空的root,是不可以的。以下这种解法是O(n^2). 用全局变量index,扫一遍,那么就是O(N)的;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode str2tree(String s) {
        if(s == null || s.isEmpty()) {
            return null;
        }
        int i = s.indexOf('(');
        if(i == -1) {
            return new TreeNode(Integer.parseInt(s));
        }
        TreeNode root = new TreeNode(Integer.parseInt(s.substring(0, i)));
        
        int j = i;
        int count = 0;
        while(j < s.length()) {
            if(s.charAt(j) == '(') {
                count++;
            }
            if(s.charAt(j) == ')') {
                count--;
            }
            if(count == 0) {
                break;
            }
            j++;
        }
        root.left = str2tree(s.substring(i + 1, j));
        // 左边有括号,那么右边肯定有对应的括号,所以去掉头尾;否则下一次循环会出现空root;
        if(j < s.length() - 1) {
             root.right = str2tree(s.substring(j + 2, s.length() - 1));
        }
        return root;
        
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值