lintcode--880. 字符串构造二叉树

描述

您需要从包含括号和整数的字符串中构造一个二叉树。
整个的输入表示一个二叉树。它包含一个整数,或零,或两对括号。该整数表示根的值,而一对括号包含一个具有相同结构的子二叉树。
如果父节点存在,您总是首先开始构造它的左子节点。

在输入字符串中只有'('')''-''0' ~ '9'。
空树表示为“”而不是“()”。

样例

给定 s = “4(2(3)(1))(6(5))”, 返回表示下面树的节点:

       4
     /   \
    2     6
   / \   / 
  3   1 5  

代码

使用栈来存储二叉树的节点,然后遇到左括号,随后读取该括号后面的数字,并且形成TreeNode节点,然后读取栈顶元素(头结点),并且把该节点连接到左指针或右指针中。如果遇到右括号,直接把栈顶元素弹出。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
import java.util.*;
public class Solution {
    /**
     * @param s: a string
     * @return: a root of this tree
     */
    int i=0;
    public TreeNode str2tree(String s) {
        // write your code here
        if("".equals(s)){
            return null;
        }
        Stack<TreeNode> nodes=new Stack<>();
        TreeNode root=null;
        while(i<s.length()){
            char ch=s.charAt(i);
            if(ch==')'){
                nodes.pop();
                i++;
            }
            else if(ch=='('){
                i++;
                int val=getVal(s);
                TreeNode q=new TreeNode(val);
                TreeNode temp=nodes.peek();
                if(temp.left==null){
                    temp.left=q;
                }else if(temp.right==null){
                    temp.right=q;
                }
                nodes.push(q);
            }
            else if(ch=='-'||(ch>='0'&&ch<='9')){
                int val=getVal(s);
                if(root==null){
                    root=new TreeNode(val);
                    nodes.push(root);
                }
            }
        }
        return root;
    }
    private int getVal(String s){
        StringBuilder num=new StringBuilder();
        boolean positive=true;
        char ch=s.charAt(i);
        if(ch=='-'){
            i++;
            positive=false;
        }
        while(i<s.length()&&(s.charAt(i)>='0'&&s.charAt(i)<='9')){
            num.append(s.charAt(i++));
        }
        int temp=Integer.valueOf(num.toString());
        return positive==true?temp:-temp;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值