zoukankan      html  css  js  c++  java
  • build tree with balanced parenthesis

    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);
        }
    

      

      

  • 相关阅读:
    查看 lib 库信息
    评委打分(C++ 容器综合练习)
    二阶段12.16
    对搜狗输入法的使用心得
    二阶段12.14
    二阶段12.13
    二阶段12.12
    典型用户描述
    水王(课堂练习)
    一阶段11.21
  • 原文地址:https://www.cnblogs.com/apanda009/p/7965405.html
Copyright © 2011-2022 走看看