public static List <string> BfsPathLevelTraversal(NTreeNode root) { if (root == null) { return(null); } List <string> levelList = new List <string>(); Queue <NTreeNode> levelQueue = new Queue <NTreeNode>(); levelQueue.Enqueue(root); while (levelQueue.Count > 0) { int leveLength = levelQueue.Count; string levelString = string.Empty; for (int i = 0; i < leveLength; i++) { var levelItem = levelQueue.Dequeue(); levelString += "-" + levelItem.val; if (levelItem.Children != null) { levelItem.Children.ForEach(x => { levelQueue.Enqueue(x); }); } } levelList.Add(levelString); } return(levelList); }
public static void DfsPath(NTreeNode root, NTreeNode target, List <int> pathList) { if (root == null) { pathList = new List <int>(); return; } pathList.Add(root.val); if (root.val == target.val) { return; } foreach (var child in root.Children) { DfsPath(child, target, pathList); } }