Binary Tree depth

Source: Internet
Author: User

Enter a binary tree to 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 and right children 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 idea: There is no idea, that is, tree traversal. Code AC: [cpp] # include <stdio. h> # include <stdlib. h> typedef struct tree {int id; int vi; int lc; int rc;} tree, * p_tree; int n; p_tree t; int level; void fun (int idx, int l) {int tmp; if (t [idx]. lc =-1 & t [idx]. rc =-1) {if (l> level) {level = l ;}} else {if (t [idx]. rc <= n & t [idx]. rc> = 1) {fun (t [idx]. rc-1, l + 1);} if (t [idx]. lc <= N & t [idx]. lc> = 1) {fun (t [idx]. lc-1, l + 1) ;}} int main () {int I; while (scanf ("% d", & n )! = EOF) {www.2cto.com t = (p_tree) malloc (sizeof (tree) * n); for (I = 0; I <n; I ++) {t [I]. id = I + 1; scanf ("% d", & t [I]. lc, & t [I]. rc);} level =-1; fun (0, 1); printf ("% d \ n", level);} 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: 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.