1. 程式人生 >實用技巧 >其它 >#力扣 LeetCode589. N 叉樹的前序遍歷 @FDDLC

#力扣 LeetCode589. N 叉樹的前序遍歷 @FDDLC


題目描述:

589. N 叉樹的前序遍歷 - 力扣(LeetCode) (leetcode-cn.com)

Java程式碼:遞迴

/*
// 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 {
    List<Integer> ans=new LinkedList<>();
    public List<Integer> preorder(Node t) {
        if(t==null)return ans;
        ans.add(t.val);
        for(Node e:t.children)preorder(e);
        return ans;
    }
}

#力扣 LeetCode589. N 叉樹的前序遍歷 @FDDLC

Java程式碼二:非遞迴

class Solution {
    public List<Integer> preorder(Node t) {
        List<Integer> ans=new LinkedList<>();
        LinkedList<Node> stack=new LinkedList<>(),curStack=new LinkedList<>();
        if(t!=null)stack.push(t);
        while(!stack.isEmpty()){
            Node cur=stack.pop();
            ans.add(cur.val);
            for(Node child:cur.children)curStack.push(child);
            while(!curStack.isEmpty())stack.push(curStack.pop());
        }
        return ans;
    }
}

#力扣 LeetCode589. N 叉樹的前序遍歷 @FDDLC