首页 技术 正文
技术 2022年11月12日
0 收藏 918 点赞 5,087 浏览 1589 个字

536. Construct Binary Tree from String

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.

算法分析:

在 class Solution 内声明一个 int index=0,用来标记当前应该考察的输入字符串的下标,如果下标所指示的是数字,则读取数字,并增进下标;如果下标所指示的是'(‘,则需要递归调用生成TreeNode的函数,并将结果放在root.left子树中;如果当前字符为’)’,则当前递归调用结束,将 index 增加 1 ,并返回生成的 TreeNode。

在父级的函数调用中,将返回的TreeNode放在root.left,考差当前 index 所指示的字符,如果为'(‘,则继续递归调用函数来生成右子树;如果为’)’,说明当前子树没有右子树,将 index 增加 1,并返回当前TreeNode。

Java 算法实现:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int index=0;
public TreeNode str2tree(String s) {
int len=s.length();
if(len<1||index>=len){
return null;
}
int val=0;
int ch;
int sign=1;
if(s.charAt(index)=='-'){
sign=-1;
index++;
}
while(index<len&&(ch=s.charAt(index))<='9'&&ch>='0'){
val*=10;
val+=ch-'0';
index++;
}
TreeNode root=new TreeNode(sign*val);
if(index>=len||s.charAt(index)==')'){
index++;
return root;//have no child
}//here now index is pointing to a '(' index++;//now pointing to a number
root.left=str2tree(s);
if(index>=len||s.charAt(index)==')'){
index++;
return root;
}//here it means index is pointing to '('
index++;
root.right=str2tree(s);
if(index>=len||s.charAt(index)==')'){
index++;
}
return root;
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,489
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,904
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,737
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,490
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,128
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,291