码迷,mamicode.com
首页 > 其他好文 > 详细

build tree with balanced parenthesis

时间:2017-12-03 11:44:00      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:val   bsp   contain   nta   main   for   sharp   string   exp   

 

Given a tree string expression in balanced parenthesis format:
[A[B[C][D]][E][F]].
Construct a tree and return the root of the tree.
                A
            /   |  \
          B    E   F
         / \
       C   D

 

public void buildGra(String s) {
        int count = 0;
        Map<Integer, ArrayList<Node>> map = new HashMap<>();
        for (char c : s.toCharArray()) {
            if (c == ‘[‘) {
                count++;
            } else if (c == ‘]‘) {
                count--;
            } else {
                if (!map.containsKey(count)) {
                    map.put(count, new ArrayList<Node>());
                }
                Node n = new Node(c);
                map.get(count).add(n);
                if (map.containsKey(count - 1)) {

                    ArrayList<Node> cur = map.get(count - 1);
                    cur.get(cur.size() - 1).children.add(n);
                }
            }

        }
        Node root = map.get(1).iterator().next();
        for (int i = 0; i < root.children.size(); i++) {
            Node nn = root.children.get(i);
            System.out.println(nn.val);
            root = nn;
        }
    }
    public static void main(String[] args) {
        String s = "[A[B[C][D]][E][F]]";
        Groph g = new Groph();
        g.buildGra(s);
    }

  

  

build tree with balanced parenthesis

标签:val   bsp   contain   nta   main   for   sharp   string   exp   

原文地址:http://www.cnblogs.com/apanda009/p/7965405.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!