1. Implementation of the number of nodes in the binary tree:
1, define function: count(node):
1. Count the number of nodes in the binary tree with node as the root node;
2, function code implementation:
1 /* Function defining the number of data nodes */ 2 int count(BTreeNode<T>* node) const 3 { 4 return (node != NULL) ? (count(node->left) + count(node->right) + 1) : 0 ; 5 }
3. Implementation of member function code:
1 int count() const
2 {
3 return count(root());
4 }
2. Height of binary tree:
1, define function: height(node):
Get the height of the binary tree with node as the root node;
2. Function code implementation:
1 /* Define the height of binary tree with node as root node */ 2 int height(BTreeNode<T>* node) const 3 { 4 int ret = 0; 5 6 if( node != NULL ) // Null node returns 0, recursive exit 7 { 8 int lh = height(node->left); 9 int rh = height(node->right); 10 ret = ((lh > rh) ? lh : rh) + 1; 11 } 12 13 return ret; 14 }
3. Implementation of member function code:
1 int height() const
2 {
3 return height(root());
4 }
3. Degree of tree:
1, define function: degree(node):
Get the degree of the binary tree with node as the root node;
2, function code implementation:
1 /* Define the degree of binary tree with node as root node */ 2 int degree(BTreeNode<T>* node) const 3 { 4 int ret = 0; 5 6 if( node != NULL ) 7 { 8 // Very subtle rewriting, from bottom to top; 9 BTreeNode<T>* child[] = { node->left, node->right}; 10 ret = (!!node->left + !!node->right); // Degree of node number 11 12 for(int i=0; (i<2) && (ret<2); i++) //After the degree of nodes meets the requirements, it is not required directly 13 { 14 int d = degree(child[i]); 15 16 if( ret < d ) 17 { 18 ret = d; 19 } 20 } 21 } 22 23 return ret; 24 }
3. Implementation of function code:
1 int degree() const
2 {
3 return degree(root());
4 }