Title Description
If we look at the two-fork tree as a graph, and the connection between the parent and child nodes is two-way, we'll define the "distance" as a variable between the two nodes.
Write a program to find the distance between the two nodes farthest apart in a binary tree.
Input requirements
The first line of the input contains a separate number T, indicating the number of test sequences;
Each of the following behaviors is a test sequence in which the test sequence enters characters in a sequential sequence, and if the node has no left or right child, the input is represented by a space, and the last line is ended with a space.
Output requirements
The distance between the two nodes farthest apart from the output binary tree
If the input
2
ABC DE G F
-+a *b-c d/e F
should be output
4
6
Draw on a lot of code, finally excellent deepth () to the simplest already, the idea is to traverse each node, the empty node is-1, the final result is definitely a node of the left subtree depth plus the right subtree depth plus 2, so the depth of each node Saozi right subtree, take the sum of the subtree depth and add 2 maximum.
Code:
#include <bits/stdc++.h>using namespace std;typedef struct btree{char data; struct BTree *left,*right;} BTree; BTree *creatbtree () {char ch=getchar (); if (ch== ') return NULL; BTree *temp= (BTree *) malloc (sizeof (BTree)); temp->data=ch; Temp->left=creatbtree (); Temp->right=creatbtree (); return temp;} int deepth (BTree *t,int &maxdis) {if (! T) return-1; int l=deepth (T->LEFT,MAXDIS); int r=deepth (T->RIGHT,MAXDIS); Maxdis=max (maxdis,l+r+2); Return Max (L,r) +1;} void Delbtree (BTree *p) {if (p) {delbtree (p->left); Delbtree (P->right); Free (p); }}int Main () {int t; cin>>t; while (t--) {GetChar ();//eat carriage return int maxdis=-1; BTree *root=creatbtree (); GetChar ();//Eat the Last trailing space deepth (Root,maxdis); cout<<maxdis<<endl; Delbtree (root); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Finding the maximum distance of a node in a binary tree