LeetCode590. N叉树的后序遍历

版权声明: https://blog.csdn.net/weixin_40550726/article/details/82995873

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

例如,给定一个 3叉树 :

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

说明: 递归法很简单,你可以使用迭代法完成此题吗?


思路:采用递归的思想遍历n叉树。

/*
// 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> res=new LinkedList<Integer>();
        postorderTraversal(res,root);
        return res;
    }
     public  void postorderTraversal(List<Integer> res,Node root){
        if(null==root){
            return ;
        }
        if(null!=root.children&&root.children.size()>0){
            postorderTraversal(res,root.children.get(0));
        }
        for(int i=1;i<root.children.size();i++){
            postorderTraversal(res,root.children.get(i));
        }
        res.add(root.val);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40550726/article/details/82995873