build tree with balanced parenthesis

Posted apanda009

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }

  

  

以上是关于build tree with balanced parenthesis的主要内容,如果未能解决你的问题,请参考以下文章

Balanced Binary Tree

[Leetcode] Balanced Binary Tree

110. Balanced Binary Tree

LC.110. Balanced Binary Tree

110. Balanced Binary Tree

Leetcode[110]-Balanced Binary Tree