Binary Tree depth

Source: Internet
Author: User
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.


/* 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 ;}

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: 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.