leetcode.590 N叉树的后序遍历

给定一个 N 叉树,返回其节点值的后序遍历

例如,给定一个 3叉树 :

返回其后序遍历: [5,6,3,2,4,1].

思路:类似于二叉树的后序遍历,利用递归实现。

代码:

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    List<Integer> list = new ArrayList<>();
    public List<Integer> postorder(Node root) {
        if(root == null) return;
        for(Node child:root.children){
            postorder(child);
        }
        list.add(root.val);
        return list;
    }
}

非递归实现:利用栈结构保存每一个结点

代码:

执行用时为 2 ms 的范例
/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {  
    public List<Integer> postorder(Node root) {
         List<Integer> list = new ArrayList();
         Stack<Node> stack = new Stack<>();
         Node pre = null;

        stack.push(root);
        while(stack != null){
            Node curr = stack.peek();
            if(curr.children.size() == 0 || (pre!=null && curr.children.contains(pre))){
                list.add(curr.val);
                pre = curr;
                stack.pop();
            }else{
                for(int i = curr.children.size()-1;i>=0;i++){
                    stack.push(cur.children.get(i));
                }
            }            
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40904220/article/details/84476673
今日推荐