# {Data structure} calculates the number of leaf nodes in a binary tree.

Source: Internet
Author: User

/*************************************** ***********

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 **************************/
Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.