LeetCode:Diameter of Binary Tree
543. Diameter of Binary Tree
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1 / \ 2 3 / \ 4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
思路:这个题目的思路还是比较直接的,记录下每个节点的深度以及以当前节点为连接点的最大长度,遍历一遍取最大值即可。
1 struct res{ 2 int d; 3 int m; 4 res(int depth, int max) :d(depth), m(max){} 5 }; 6 struct res diaOfBinaryTree(TreeNode* t,int* dia) 7 { 8 if (t == NULL) 9 { 10 struct res res(0, 0); 11 return res; 12 } 13 struct res l = diaOfBinaryTree(t->left,dia); 14 struct res r = diaOfBinaryTree(t->right,dia); 15 struct res res(max(l.d,r.d)+1,l.d+r.d+1); 16 *dia = max(*dia, l.d + r.d + 1); 17 return res; 18 } 19 int diameterOfBinaryTree(TreeNode* root) { 20 int dia = 0; 21 diaOfBinaryTree(root, &dia); 22 return dia; 23 }
如果你有任何疑问或新的想法,欢迎在下方评论。