Operations on N-ary Trees

A tree whose parent node has and at most two children is called a binary tree, and an N-ary tree is a parent node with N children.
Since an N-ary tree has multiple child nodes, there is no in-order traversal, only pre-order traversal, post-order traversal, and level-order traversal are left.


preorder traversal

Similar to a binary tree, the order of traversal is
root node - left child node - other child nodes - right child node

The result of preorder traversal: [1,3,5,6,2,4]

    public List<Integer> preorder(Node root) {
        List<Integer> list=new ArrayList<Integer>();
        if(root==null){
            return list;
        }
        list.add(root.val);
        for(int i=0;i<root.children.size();i++){
            list.addAll(preorder(root.children.get(i)));
        }

        return list;
    }

post-order traversal

After the child node is placed before the root node, the result of the
post : [5,6,3,2,4,1]

    public List<Integer> postorder(Node root) {
        ArrayList<Integer> list=new ArrayList<Integer>();
        if(root==null){
            return list;
        }

        for(int i=0;i<root.children.size();i++){
            list.addAll(postorder(root.children.get(i)));
        }
        list.add(root.val);

        return list;
    }

level-order traversal

The result of the level-order traversal:
[
[1],
[3,2,4],
[5,6]
]

    public List<List<Integer>> levelOrder(Node root) {
        ArrayList<Integer> levelList=new ArrayList<Integer>();
        ArrayList<List<Integer>> list=new ArrayList<List<Integer>>();

        LinkedList<Node> stack=new LinkedList<Node>();
        stack.offer(root);
        while(!stack.isEmpty()){
            int size=stack.size();
            for(int i=0;i<size;i++){
                Node node=stack.poll();
                if(node==null)continue;
                for(int j=0;j<node.children.size();j++){
                    stack.offer(node.children.get(j));
                }
                levelList.add(node.val);
            }
            if(levelList.size()>0)
            list.add(levelList);
            levelList=new ArrayList<Integer>();
        }
        return list;
    }

Depth of N-ary tree

    public int maxDepth(Node root) {
        if(root==null){
            return 0;
        }
        int max=0;
        for(int i=0;i<root.children.size();i++){
            int temp=maxDepth(root.children.get(i));
            if(temp>max){
                max=temp;
            }
        }
        return max+1;
    }

Since the N-ary tree has no special properties, there are not many common operations. All the code is in GitHub , and the serialization used is Json.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325993998&siteId=291194637