Calculate the depth of a binary tree and the number of nodes.

Source: Internet
Author: User

Calculate the depth of a binary tree and the number of nodes.

// Algorithm 5.5 calculates the depth of a binary tree and the number of nodes. # Include <iostream> using namespace std; // binary tree binary linked list storage represents typedef struct BiNode {char data; // node data field struct BiNode * lchild, * rchild; // left and right child pointer} BiTNode, * BiTree; // Use algorithm 5.3 to create a binary linked list void CreateBiTree (BiTree & T) {// enter the node value (one character) in the binary tree in the first order, and create the binary tree Tchar ch represented by the binary linked list; cin> ch; if (ch = '#') T = NULL; // recursive end, empty tree else {T = new BiTNode; T-> data = ch; // Generate the root node CreateBiTree (T-> lchild); // recursively create the left subtree CreateBiTree (T-> rchild ); // recursively create the right subtree} // else} // CreateBiTreeint Depth (BiTree T) {int m, n; if (T = NULL) return 0; // if it is an empty tree, the Depth is 0, and the recursive end else {m = Depth (T-> lchild ); // recursively calculate the Depth of the left subtree as mn = Depth (T-> rchild); // recursively calculate the Depth of the right subtree as nif (m> n) return (m + 1); // The depth of the binary tree is m and n plus 1 else return (n + 1);} int NodeCount (BiTree T) {if (T = NULL) return 0; else return NodeCount (T-> lchild) + NodeCount (T-> rchild) + 1;} void main () {BiTree tree; cout <"Enter the sequence for creating a binary linked list: \ n"; CreateBiTree (tree); cout <"the Depth of the number is:" <Depth (tree) <endl; cout <"number of nodes:" <NodeCount (tree) <endl ;}


 

Calculate the depth of a binary tree and the number of 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.