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.