Since I'm still testing this implementation, no promises without errors. If there are special problems with the implementation, I am happy to receive feedback.
At first, I get positive results:
#region CountNode utility private int CountNode(Node node, Direction d) { Func<Direction, Node> leaf = (dir) => { return dir == Direction.Left ? node.Left : node.Right; }; var done = leaf(d) == null; var root = node; var stack = new Stack<Node>( ); var count = 0; while(!done) { if (node != null) { stack.Push(node); node = leaf(d); } else { if(stack.Count > 0) { node = stack.Pop( ); // back to root, time to quit if(node == root) { done = true; continue; } // count nodes when popped ++count; // flip direction var flip = d == Direction.Left ? Direction.Right : Direction.Left; // get the leaf node node = leaf(flip); } else { done = true; } } } return count; }
Using:
var actLeftCount = CountNode(root, Direction.Left); var actRightCount = CountNode(root, Direction.Right);
This has a particular advantage when counting only nodes on Left . I can pass any node to the method and get statistics for it.
source share