589. N叉树的前序遍历

2019-08-07  本文已影响0人  衣锦昼行

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

例如,给定一个 3叉树 :

narytreeexample.png

返回其前序遍历: [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> ans = new ArrayList<>();
        if(root == null)
            return ans;
        Pre(root,ans);
        return ans;

    }
    public void Pre(Node node,List<Integer> ans){
        if(node == null)
            return;
        ans.add(node.val);
        for (Node node1 : node.children){
            Pre(node1,ans);
        }
    }
}
2.迭代

public List<Integer> preorder2(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);
        //将该节点的子节点从右往左压入栈
        List<Node> nodeList = cur.children;
        for (int i = nodeList.size() - 1; i >= 0; i--) {
            stack.push(nodeList.get(i));
        }
    }
    return res;
}
上一篇 下一篇

猜你喜欢

热点阅读