Concept:
1. Binary Tree depth: the maximum hierarchy of nodes in the tree is called the depth or height of the tree. 2. Binary Tree hierarchy: defined from the root, the root is the first layer, the root child is the second layer, and so on. Key points: 1. recursion. 2. The depth of the binary tree is greater than that of the left and right Subtrees.
Code:
/* Calculate the depth of a binary tree by rowandjj2014/7/13 --------------------------------- topic Description: enter a binary tree and find the depth of the tree. A tree path is formed from the root node to the leaf node. The longest path length is the depth of the tree. Input: Enter N in the first line. N indicates the number of knots. The node number ranges from 1 to n. The root node is 1. N <= 10. Next there are n rows. Each row has two integers A and B, indicating the left child and right child of the I node. A is the left child, B is the right child. When a is-1, there is no left child. When B is-1, there is no right child. Output: an integer indicating the depth of the tree. Sample input: 32 3-1-1-1-1 sample output: 2 */# include <iostream> # include <stdlib. h> using namespace STD; typedef struct _ node _ // use an array to store {int L; // store the int R of the left child; // store the serial number of the right child} treenode, * ptree; int getdepth (ptree T, int index) {If (! T) {return 0;} If (Index =-1) {return 0;} int NL = getdepth (t, t [Index]. l); int RL = getdepth (t, t [Index]. r); Return (NL> RL )? NL + 1: RL + 1;} int main () {int N; int L, R; // the sequence number of the left and right children while (CIN> N) {ptree Pt = (treenode *) malloc (N * sizeof (treenode); If (! Pt) {exit (-1) ;}for (INT I = 0; I <n; I ++) {CIN >>l> r; Pt [I]. L = (L =-1 )? -1 L-1; Pt [I]. r = (r =-1 )? -1: R-1;} cout <getdepth (PT, 0);} return 0 ;}