Loading…
Loading…
Walks down from the root, going left or right by comparing the target to each node — O(log n) on a balanced tree.
Search the BST for 40, starting at the root.
1Node search(Node node, int target) {2 while (node != null) { // Walk until we fall off3 if (target == node.val) return node; // Match found, return it4 else if (target < node.val) node = node.left; // Smaller, go left5 else node = node.right; // Larger, go right6 }7 return null; // Not in the tree8}