public int GetHeight(ITreeNavigator navigator, ITreeNode root) { // Check if the root node exists if (navigator.IsNull(root)) { return 0; } // Calculate the height of the left and right subtree int leftHeight = GetHeight(navigator, navigator.GetChild(root, 0)); int rightHeight = GetHeight(navigator, navigator.GetChild(root, 1)); // Return the maximum height return 1 + Math.Max(leftHeight, rightHeight); }
public int CountNodes(ITreeNavigator navigator, ITreeNode root) { if (navigator.IsNull(root)) { return 0; } // Count the number of nodes in the left and right subtree int leftCount = CountNodes(navigator, navigator.GetChild(root, 0)); int rightCount = CountNodes(navigator, navigator.GetChild(root, 1)); // Return the total number of nodes return 1 + leftCount + rightCount; }This example also uses ITreeNavigator to traverse a tree and count its nodes. It recursively visits each node of the tree and counts the number of nodes in its left and right subtrees. The total number of nodes is returned. Package library: Microsoft.Toolkit.Parsers.