N叉樹——前序遍歷

weixin_33912246發表於2018-06-04

給定一個N叉樹,返回其節點值的前序遍歷。
例如,給定一個 3叉樹 :


7260028-53f75b4635777dce.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 {
    
    List<Integer> result = new ArrayList<Integer>();
        
    public List<Integer> preorder(Node root) {
        if (root == null) return result;
        preOrderNarrTree(root);
        return result;        
    }
    
    private void preOrderNarrTree(Node root) {
        result.add(root.val);
        for (Node chil : root.children) {
            preOrderNarrTree(chil);
        }
        
    }
    
}

相關文章