Suppose we know that for the left son of the node after traversing downwardly the largest number of nodes L (i.e., the left son of the root of the subtree depth) thereof and a right son is traversed downward through the most nodes R (i.e. to the right son the depth of the root of the subtree), then to the node as the starting point of the path passes through a maximum number of nodes is the L + R + 1
We note node node as the starting point of the path passes through a maximum number of nodes is dnode, then the binary tree diameter is the maximum of all nodes dnode minus one.
The final algorithm process: We define a recursive function depth (node) function returns the node calculates dnode depth of the root of the subtree. Recursive call to the left and right son son depth L and RR are determined subtree root, the depth of the root node of the subtree that is, max (L, R) +1; dnode value of the node is L + R + 1 recursively search every node and set a global variable record ans dnode most large value, and finally return ans-1 is the diameter of the tree.
Link: https: //leetcode-cn.com/problems/diameter-of-binary-tree/solution/er-cha-shu-de-zhi-jing-by-leetcode-solution/
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int length=0; 13 int diameterOfBinaryTree(TreeNode* root) { 14 depth(root); 15 return length; 16 } 17 int depth(TreeNode* root) 18 { 19 int L=depth(root->left); 20 int R=depth(root-right); 21 length=max(L+R,length); 22 return max(L,R)+1; 23 } 24 };