Leetcode 589 N叉树的前序遍历

Leetcode 589 N叉树的前序遍历

数据结构定义:

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

例如,给定一个 3叉树 :
                  1
               /  |  
              3   2   4
             /  
            5   6 
返回其前序遍历: [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) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

递归方式:

class Solution {
    private List<Integer> ans = new ArrayList<>();
    public List<Integer> preorder(Node root) {
        dfs(root);
        return ans;
    }
    private void dfs(Node root){
        if(root == null)
            return;
        ans.add(root.val);
        for(Node child:root.children){
            dfs(child);
        }
    }
}

迭代方式:

class Solution {
    public List<Integer> preorder(Node root) {
        List<Integer> result = new ArrayList<>();
        Deque<Node> stack  = new LinkedList<>();
        if(root == null){
            return result;
        }
        stack.offer(root);
        while(!stack.isEmpty()){
            Node node = stack.poll();
            result.add(node.val);
            for(int i = node.children.size()-1; i >= 0; --i){
                stack.addFirst(node.children.get(i));
            }
        }
        return result;
    }
}
原文地址:https://www.cnblogs.com/CodingXu-jie/p/14109509.html