public static Tree GetNodeByValue(int val) { if( !nodeByValue.ContainsKey(val) ) { nodeByValue [val] = new Tree(val); } return nodeByValue [val]; }
public static void GetFurthestNode(ref Tree FurthestNode, Tree parent, int depth=0) { if( depth > MaxDepth ) { MaxDepth = depth; FurthestNode = parent; } foreach (var child in parent.Children) { GetFurthestNode(ref FurthestNode, child, depth+1); } }
public static int GetSumSubtree(int sum, ref List<Tree> CorrectParents, Tree node) { int SubtreeSum = node.Value; foreach (var child in node.Children) { SubtreeSum += GetSumSubtree (sum, ref CorrectParents, child); } if (sum == SubtreeSum) { CorrectParents.Add (node); } return SubtreeSum; }
public static void GetSumPath(int sum, ref List<Tree> CorrectLeafs, Tree node) { sum -= node.Value; if (IsLeaf( node ) ) { if (0 == sum) { CorrectLeafs.Add (node); } } else { foreach (var child in node.Children) { GetSumPath (sum, ref CorrectLeafs, child); } } }
public static bool IsLeaf(Tree node) { return null != node.Parent && 0 == node.Children.Count; }
public static int PrintPathTo(Tree node) { int depth = 0; var path = new Stack<int>(); while (null != node) { path.Push (node.Value); node = node.Parent; depth++; } while( path.Count > 1 ) { Console.Write("{0} -> ", path.Pop()); } Console.WriteLine ("{0}", path.Pop ()); return depth; }
public static bool IsRoot(Tree node) { return null == node.Parent; }
public static bool IsMiddleNode(Tree node) { return null != node.Parent && node.Children.Count > 0; }