1. 程式人生 > >C#N叉數的遍歷

C#N叉數的遍歷

C# N叉數的遍歷

結點:

// Definition for a Node.
public class Node {
    public int val;
    public IList<Node> children;
    public Node(){}
    public Node(int _val,IList<Node> _children) {
        val = _val;
        children = _children;
}

前序遍歷:

public class Solution {
    public IList<int>
Preorder(Node root) { IList<int> res = new List<int>(); if(root == null) return res; res.Add(root.val); for(int i = 0; i < root.children.Count; i++){ IList<int> temp = Preorder(root.children[i]); if(temp != null){ foreach
(var item in temp){ res.Add(item); } } } return res; } }

後序遍歷

public class Solution {
    public IList<int> Preorder(Node root) {
        IList<int> res = new List<int>();
        if(root == null)   return res;
        for
(int i = 0; i < root.children.Count; i++){ IList<int> temp = Preorder(root.children[i]); if(temp != null){ foreach(var item in temp){ res.Add(item); } } } res.Add(root.val); return res; } }