Recursively traverse a binary tree to calculate the height, number of nodes, and number of leaf nodes

Source: Internet
Author: User
# Include <iostream> # include <cstdio> # include <algorithm> # include <cstdlib> using namespace std; struct Node {char data; Node * lchild; Node * rchild ;}; int nodes (Node * T) {if (T = NULL) return 0; else if (T-> lchild = NULL & T-> rchild = NULL) return 1; else return nodes (T-> lchild) + nodes (T-> rchild) + 1;} void CountLeaf (Node * T, int & num) {if (T! = NULL) {if (T-> lchild = NULL & T-> rchild = NULL) num ++; CountLeaf (T-> lchild, num ); countLeaf (T-> rchild, num) ;}} void High (Node * T, int & h) {if (T = NULL) h = 0; else {int left_h; high (T-> lchild, left_h); int right_h; High (T-> rchild, right_h); h = 1 + max (left_h, right_h );}} node * CreateBiTree (Node * & T) {char ch; cin> ch; if (ch = '#') T = NULL; else {if (! (T = (Node *) malloc (sizeof (Node) return 0; T-> data = ch; CreateBiTree (T-> lchild ); createBiTree (T-> rchild); return T ;}} void Free (Node * & T) {if (T = NULL) return; Free (T-> lchild ); // T-> lchild = NULL; Free (T-> rchild); // T-> rchild = NULL; free (T); T = NULL;} int main () {Node * T = NULL; CreateBiTree (T); int num = 0; int height; High (T, height); cout 

Recursively traverse a binary tree to calculate the height, number of nodes, and number of leaf nodes

Contact Us

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.