/*************************************** ***********
Algorithm Description: Write a recursive algorithm to calculate the number of leaf nodes in a binary tree (6.42) **************************************** * ***********/INT leaf (bitree T) {If (! T) return 0; // empty tree, no leaf else if (! T-> LCH &&! T-> RCH) return 1; else return (leaf (t-> LCH) + leaf (t-> RCH ));} /*********************** algorithm analysis: first of all, you must understand the essence of algorithm analysis is binary tree traversal. only outputs with additional conditions. find the leaf node and count it. 1. when it comes to counting, the first reaction is to create an int variable (such as Count), and then find a qualified variable to perform count ++; but it is not so appropriate here. if recursive traversal is selected, a count is created each time a recursive function is called, and each count is different. it will also be initialized to 0, which makes no sense. 2. so the method is to use the function return value. define a function as a function whose return value is int type. 3. then judge: If (! T-> LCH &&! T-> RCH) If both the left and right nodes are null, 1 (that is, Count + 1) is returned ). otherwise, the recursive function is called. First the left subtree and then the right subtree. the true essence of this algorithm is: Return (leaf (t-> LCH) + leaf (t-> RCH )); when recursion is called, the return values of all recursive functions are added. the value returned to the main function is the number of leaf nodes! Clever!: D **************************/