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

例如,给定一个 3叉树 :

 

589,N叉树的前序遍历

 

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

 

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

 

/*
// 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> preorder(Node root) {
        List<Integer> res=new ArrayList<>();
         preorder(root, res);
        return res;    
        
    }
private  void preorder(Node root, List<Integer> res) {
        if(root == null) {
            return;
        }
        res.add(root.val);
        //for(final Node n : root.children)
         for(int i=0;i<root.children.size();i++)
        preorder(root.children.get(i), res);
    }
}

 

 

 

相关文章:

  • 2021-10-15
  • 2022-01-09
  • 2022-02-03
  • 2022-02-10
  • 2022-12-23
  • 2021-09-22
  • 2021-06-09
  • 2021-09-09
猜你喜欢
  • 2022-01-11
  • 2021-11-24
  • 2021-06-17
  • 2021-04-24
  • 2021-05-06
  • 2021-12-23
相关资源
相似解决方案