private void SerializeUsingDictionary(NaryNode root, ref Dictionary <int, IList <int> > dict) { if (root == null) { return; } if (root.children != null) { foreach (var child in root.children) { if (child != null) { if (dict.ContainsKey(root.val)) { dict[root.val].Add(child.val); } else { dict[root.val] = new List <int>() { child.val }; } } SerializeUsingDictionary(child, ref dict); } } }
private void LevelOrderTraversal(NaryNode root) { if (root == null) { return; } Queue <NaryNode> queue = new Queue <NaryNode>(); queue.Enqueue(root); while (queue.Count > 0) { NaryNode cur = queue.Dequeue(); Console.WriteLine(cur.val); if (cur.children != null) { foreach (var child in cur.children) { if (child != null) { queue.Enqueue(child); } } } } }
private void PostOrderTraversalRecur(NaryNode root) { if (root == null) { return; } if (root.children != null) { foreach (var child in root.children) { PostOrderTraversalRecur(child); } } Console.WriteLine(root.val); }
private void InsertNode(NaryNode root, int value, int parentValue = -1) { if (root == null) { if (parentValue == -1) { this.root = new NaryNode(value); } return; } if (root.val == parentValue) { if (root.children == null) { root.children = new List <NaryNode>() { new NaryNode(value) } } ; else { root.children.Add(new NaryNode(value)); } return; } if (root.children != null) { foreach (var child in root.children) { if (child != null) { InsertNode(child, value, parentValue); } } } }
public NaryTree() { root = null; }
public NaryNodeWithLevel(NaryNode n, int l) { node = n; level = l; }
private string SerializeLevel(NaryNode root) { if (root == null) { return("null"); } List <string> resultList = new List <string>(); Queue <NaryNodeWithLevel> queue = new Queue <NaryNodeWithLevel>(); queue.Enqueue(new NaryNodeWithLevel(root, 0)); queue.Enqueue(new NaryNodeWithLevel(null, 0)); int currentLevel = 0; while (queue.Count > 0) { NaryNodeWithLevel cur = queue.Dequeue(); if (currentLevel < cur.level) { currentLevel = cur.level; queue.Enqueue(new NaryNodeWithLevel(null, currentLevel)); } if (cur.node == null) { // result = string.Concat(result, " null"); resultList.Add("null"); continue; } //result = string.Concat(result, " ", cur.node.val); resultList.Add(cur.node.val.ToString()); if (cur.node.children != null) { foreach (var child in cur.node.children) { if (child != null) { queue.Enqueue(new NaryNodeWithLevel(child, cur.level + 1)); } } } else { queue.Enqueue(new NaryNodeWithLevel(null, cur.level + 1)); } } for (int i = resultList.Count - 1; i >= 0; i--) { if (resultList[i] == "null") { resultList.RemoveAt(i); } else { break; } } return(string.Join(" ", resultList)); }