589. N 叉树的前序遍历

355 阅读1分钟

题目

image.png

image.png

  • N叉树的定义
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 {
    public List<Integer> preorder(Node root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;//特判
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node cur = stack.pop();
            res.add(cur.val);
            for (int i = cur.children.size() - 1; i >= 0; i--) {//倒着入栈,这样pop的时候就是正序了
                stack.push(cur.children.get(i));//由于这里是限制再size()内,所以不用担心加入null节点
            }
        }
        return res;
    }
}

方法二:递归

class Solution {
    List<Integer> res = new ArrayList<>();
    public List<Integer> preorder(Node root) {
        dfs(root);
        return res;
    }
    public void dfs(Node root) {
        if (root == null) {//这是个特判,而不是递归终止条件
            return;
        }
        res.add(root.val);
        for (Node node : root.children) {//递归终止条件隐含在这里面
            dfs(node);
        }
    }
}