算法:N叉树的后序遍历算法分享

//1.递归
	public List postorder(Node root) {
		List list = new ArrayList();
		if (root == null) return list;
		
		post_order(list,root.children);
		list.add(root.val);
		
		return list;
    }
	
	public void post_order(List list,List subList) {
		if (subList == null || subList.size() == 0) return;
		
		for (Node n : subList) {
			if (n == null) return;
			post_order(list, n.children);
			list.add(n.val);
		}
	}
	//2.迭代
	public List postorder(Node root) {
		LinkedList input = new LinkedList<>();
		LinkedList output = new LinkedList<>();
        if (root == null) {
            return output;
        }

        input.add(root);
        while (!input.isEmpty()) {
            Node node = input.pollLast();
            output.addFirst(node.val);
            if (node.children != null) {
	            for (Node item : node.children) {
	            	if (item != null) {
	            		input.add(item);						
					}
	            }
            }
        }
        return output;		
    }

 

你可能感兴趣的:(算法:N叉树的后序遍历算法分享)