public static void TestIsTreeBalanced() { BinaryTreeNode root = new BinaryTreeNode(4); root.InsertLeft(2); root.Left.InsertLeft(1); root.InsertRight(6); // Comment following line to render tree Balanced root.Left.Left.InsertLeft(0); // The depth in the code below of 0 appears to be useless NodeDepthPair check = new NodeDepthPair(root, 0); Console.WriteLine("Given Tree is Balanced: {0}", check.IsBalanced(root)); }
public virtual void FindReachableTiles(Predicate <MapNode> expandCondition) { // Breadth first search with remaining speed as limit Reachable = new HashSet <MapNode>(); Queue <NodeDepthPair> openQ = new Queue <NodeDepthPair>(); HashSet <MapNode> openH = new HashSet <MapNode>(); openQ.Enqueue(new NodeDepthPair(Tile, -1)); openH.Add(Tile); while (openQ.Count > 0) { NodeDepthPair node = openQ.Dequeue(); if (node.Depth == Speed.Remaining) { continue; } if (expandCondition == null || expandCondition(node.Node)) { foreach (MapNode neighbor in node.Node.Neighbors) { if (Reachable.Contains(neighbor)) { continue; } if (!openH.Contains(neighbor)) { openQ.Enqueue(new NodeDepthPair(neighbor, node.Depth + 1)); openH.Add(neighbor); } } } Reachable.Add(node.Node); } }
public bool isBalanced(BinaryTreeNode treeRoot) { bool balanced = true; // Start a stack Stack <NodeDepthPair> treeStack = new Stack <NodeDepthPair>(); NodeDepthPair rootNodePair = new NodeDepthPair(treeRoot, 0); // Push in the root treeStack.Push(rootNodePair); // Declare depth holder List <int> numDepths = new List <int> (); while (treeStack.Count > 0) { NodeDepthPair curNodePair = treeStack.Pop(); Console.WriteLine("Looking at node {0}", curNodePair.node.value); // Check if this is a leaf node if (curNodePair.node.left == null && curNodePair.node.right == null) { Console.WriteLine("\tIs leaf Node at depth {0}", curNodePair.depth); // Depth is currently not represented if (!numDepths.Contains(curNodePair.depth)) { numDepths.Add(curNodePair.depth); // Conidtions for having depths that have diff greater than 1 // Number of depths is greater than 2, then we probably if (numDepths.Count > 2) { return(false); } // There are 2 depths and their diff is greater than 1 if (numDepths.Count == 2) { if (Math.Abs(numDepths[0] - numDepths[1]) > 1) { return(false); } } } } // This node has children else { // If there is a left node if (curNodePair.node.left != null) { // put that on the stack treeStack.Push(new NodeDepthPair(curNodePair.node.left, curNodePair.depth + 1)); } // If there is a left node if (curNodePair.node.right != null) { // put that on the stack treeStack.Push(new NodeDepthPair(curNodePair.node.right, curNodePair.depth + 1)); } } } return(balanced); }