Topic:
Find the farthest distance of the two nodes of the binary tree.
The binary tree is defined as follows:
Class Treenode{public: int val; Treenode* left; treenode* right; TreeNode (int x): Val (x), left (null), right (null) {}};
Ideas:
Traverse each node to find the longest path at the root of the current node, and then find the maximum value in all the longest paths.
Code:
Code Listing 1:
Class Node{public: int val; Node* left; node* right; int maxleft; int maxright;}; void longestpath_1 (node* proot,int& maxlen) { if (proot==null) return; if (proot->left==null) proot->maxleft=0; if (proot->right==null) proot->maxright=0; int Leftlen; if (proot->left) { longestpath_1 (proot->left,maxlen); Leftlen=1+max (proot->left->maxleft,proot->left->maxright); proot->maxleft=leftlen; } int Rightlen; if (proot->right) { longestpath_1 (proot->right,maxlen); Rightlen=1+max (proot->right->maxleft,proot->right->maxright); proot->maxright=rightlen; } Maxlen=max (Proot->maxleft+proot->maxright,maxlen);}
Code Listing 2:
Class Treenode{public: int val; Treenode* left; treenode* right; TreeNode (int x): Val (x), left (null), right (null) {}};void Longestpath (treenode* proot,int& maxleft,int& maxright,int& maxlen) { if (proot==null) { maxleft=0; maxright=0; maxlen=0; return; } int maxleft_1,maxleft_2,maxright_1,maxright_2; Longestpath (Proot->left,maxleft_1,maxright_1,maxlen); Longestpath (Proot->right,maxleft_2,maxright_2,maxlen); Maxleft=1+max (maxleft_1,maxright_1); Maxright=1+max (maxleft_2,maxright_2); Maxlen=max (Maxleft,maxright) +1;}
(algorithm) The maximum distance of two nodes of a binary tree