Binary Search Tree Node Count
type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // countNodesInBST recursively counts the number of nodes in a Binary Search Tree. // It traverses the tree and sums up the counts from the left and right subtrees. // This is a fundamental operation for understandin...
This function counts the total number of nodes in a Binary Search Tree (BST). It utilizes a recursive approach to traverse the tree. This is a fundamental operation for many tree-based algorithms and data analysis tasks,...
The `countNodesInBST` function calculates the total number of nodes in a Binary Search Tree using recursion. The base case for the recursion is when the `root` pointer is `nil`, indicating an empty subtree, in which case it returns 0. For a non-empty subtree, the function returns 1 (for the current node) plus the result of recursively calling itself on the left child and the right child. This ensures that every node in the tree is visited exactly once. The time complexity is O(N), where N is the number of nodes in the tree, because each node is processed once. The space complexity is O(H) in the average case and O(N) in the worst case (for a skewed tree), where H is the height of the tree, due to the recursion call stack. The algorithm correctly handles an empty tree as an edge case.
function countNodesInBST(root): if root is null: return 0 else: left_count = countNodesInBST(root.left) right_count = countNodesInBST(root.right) return 1 + left_count + right_count