Q: Given a binary tree (non-binary search tree), how long is the distance between the two most distant leaf nodes in the binary tree? The distance between the two leaves is defined as f (x, y) = sum of data of all nodes from node X to the Root Node path + sum of data of all nodes from node Y to the Root Node path-from the first ancestor node of X and Y to the Root Node path the sum of data on all nodes.
The main idea of this question:
1. Find all the leaf nodes of the binary tree.
2. Find the First Ancestor node of any two leaf nodes.
3. Calculate the path between two nodes with an ancestor-descendant relationship, and calculate the sum of node data in the path.
# Include <iostream> # include <vector> using namespace STD; struct node {node (INT data _) {DATA = data _; left = NULL; Right = NULL ;} int data; node * left; node * right;}; bool isexistpath (node * ancestor, node * descendant, vector <node *> & Path, Int & pathlen) {If (ancestor = NULL) return false; Path. push_back (ancestor); pathlen ++; If (ancestor-> left = NULL & ancestor-> right = NULL) {If (ancestor = descendant) {return True ;}} bool b1 = isexistpath (ancestor-> left, descendant, path, pathlen); bool b2 = isexistpath (ancestor-> right, descendant, path, pathlen ); if (! B1 &&! B2) {path. pop_back (); pathlen --; return false;} return true;} int calculatedistance (node * P, node * q) {vector <node *> path; int pathlen = 0; if (isexistpath (p, q, path, pathlen) {int res = 0; For (INT I = 0; I <pathlen; I ++) res + = path [I]-> data; return res ;}} static vector <node *> leafnodes; void findleafnodes (node * root) {If (root-> left = NULL & root-> right = NULL) leafnodes. push_back (Root); If (root-> left) findleafno Des (root-> left); If (root-> right) findleafnodes (root-> right);} node * LCA (node * root, node * P, node * q) // least common ancestor {node * l, * r, * TMP; If (root = NULL) return NULL; if (root-> left = p | root-> left = q | root-> right = p | root-> right = q) return root; else {L = LCA (root-> left, p, q); r = LCA (root-> right, p, q); If (L! = NULL & R! = NULL) return root; else {TMP = (L! = NULL )? L: R; return TMP ;}}int main () {node * root = new node (5); root-> left = new node (4 ); root-> left = new node (2); root-> left-> right = new node (1); root-> right = new node (3 ); root-> right-> left = new node (6); root-> right = new node (7 ); root-> right-> left = new node (8); int res = 0; int max =-1; findleafnodes (Root); For (INT I = 0; I <leafnodes. size (); I ++) for (Int J = I + 1; j <leafnodes. size (); j ++) {Node * LCA = LCA (root, leafnodes [I], leafnodes [J]); int d1 = calculatedistance (root, leafnodes [I]); int D2 = calculatedistance (LCA, leafnodes [J]); Res = D1 + D2-LCA-> data; max = res> Max? Res: Max;} cout <max <Endl; return 0 ;}