Calculate the maximum distance between nodes in the binary tree and the maximum distance between the Binary Tree
Description
If we regard a binary tree as a graph, and the line between parent and child nodes is bidirectional, we would like to define "distance" as a variable between two nodes.
Write a program to find the distance between the two nodes with the farthest distance 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 rows is a test sequence. The test sequence is a sequence of first-order input characters. If the node does not have left or right children, the input is represented by a space, end the input of a row with a space.
Output requirements
The distance between the two nodes that are the farthest in the output binary tree
Assume that
2
ABC DE G F
-+ A * B-c d/e f
Output
4
6
I learned a lot of code, and finally optimized deepth () to the simplest. The idea is to traverse each node. The empty node is-1, the final result must be the depth of the Left subtree of a node plus the depth of the right subtree plus 2, so we can find the depth of the Left subtree and the right subtree of each node, take the left and right subtree depth and the maximum value of 2.
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 the carriage return int maxDis =-1; BTree * root = CreatBTree (); getchar (); // eat the trailing space deepth (root, maxDis ); cout <maxDis <endl; delBTree (root);} return 0 ;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.