Leetcode-536. Construct Binary Tree from String

本文介绍了一种从特定格式的字符串中构建二叉树的方法。该字符串包含括号及整数,通过解析这些信息可以生成对应的二叉树结构。文章提供了一个具体的示例输入及其预期输出,并详细解释了实现过程中的关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。这次比赛略无语,没想到前3题都可以用暴力解。

博客链接:mcf171的博客

——————————————————————————————

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.
这个题目耽误了很久,主要是没太想明白这个堆的压入和压出的操作。可惜是最后超时提交,没啥用了。

public class Solution {
    public TreeNode str2tree(String s) {
        if(s.length() == 0) return null;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        int start = 0, end = 0;
        TreeNode root = null,parents = null, node = null;
        int flag = 1;
        while(start < s.length()){
            if(s.charAt(start) == '('){
                stack.push(parents); 
                start ++;
            }else if(s.charAt(start) == ')'){
                parents = stack.pop();
                if(parents.left == null) {parents.left = node;node=parents;}
                else{parents.right = node;node = parents;}
                start ++;
            }else if(s.charAt(start) == '-') {flag = -1;start ++;}
            else{
                end = findTheNum(s,start);
                int val = 0;
                for(int i = start; i < end; i ++)
                    val = val*10 + (s.charAt(i) - '0');
                node = new TreeNode(val * flag);
                start = end;
                parents = node;
                if(root == null) root = node;
                flag = 1;
            }
        }

        return root;
    }

    private int findTheNum(String s, int start){
        for(;start<s.length(); start ++)
            if((s.charAt(start) - '0') * (s.charAt(start) - '9') > 0) break;
        return start;
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值