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

      

      

  • 相关阅读:
    第八章 多线程编程
    Linked List Cycle II
    Swap Nodes in Pairs
    Container With Most Water
    Best Time to Buy and Sell Stock III
    Best Time to Buy and Sell Stock II
    Linked List Cycle
    4Sum
    3Sum
    Integer to Roman
  • 原文地址:https://www.cnblogs.com/apanda009/p/7965405.html
Copyright © 2011-2022 走看看