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 thelongestpath 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 R...
classSolution{public:// 左子树的高度+右子树的高度intmax_height =0;intdiameterOfBinaryTree(TreeNode* root){if(!root) {return0; }intleft = height(root->left);intright = height(root->right);inttmp = left + right;if(tmp > max_height) max_height = tmp; diameterOfBinaryTree(root->left...
leetcode 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 treeisthe length of the longest path between any two nodesina tree. This path mayormaynotpassthrough the root. Example: Given a binary tree1 ...
LeetCode题解之Diameter of Binary Tree 1、题目描述 2、分析 深度优先。 3、代码 1 int ans; 2 int diameterOfBinaryTree(TreeNode* root) { 3 ans = 1; 4 depth(root); 5 6 return ans - 1; 7 } 8 9 int depth(TreeNode *root){ 10 if (root == NULL) 11 return 0; 12 int L = ...
[leetcode] 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 longestpath between any two nodes in a tree. This path may or may not pass through the root....
* TreeNode right; * TreeNode(int x) { val = x; } * }*/classSolution {intmaxLen = 0;publicintdiameterOfBinaryTree(TreeNode root) { calHelper(root);returnmaxLen; }/** return the current depth. leaf node has depth of 1.*/privateintcalHelper(TreeNode root) {if(root ==null) {re...
LeetCode 543. Diameter of Binary Tree(两节点最长路径) 题意:求树上任意两节点的最长路径。分析:最长路径一定经过某个子树的根结点,显然,最长路径的两端要么是该根结点要么是叶子结点,因此,最长路径的长度一定为该子树的左子树高+右子树高。1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20...
unordered_map<TreeNode*,int>m; }; 参考资料: https://leetcode.com/problems/diameter-of-binary-tree/description/ https://leetcode.com/problems/diameter-of-binary-tree/discuss/101132/java-solution-maxdepth https://leetcode.com/problems/diameter-of-binary-tree/discuss/101115/543-diameter-of-binary...
需要两个function,因为getDepth function 返回的都是depth,不是diameter,所以需要diameterOfBinaryTree 来单独返回diameter; 每一个点的最大直径等于左边的depth 加上 右边的depth,取所有点中最大的值。 1/**2* Definition for a binary tree node.3* public class TreeNode {4* int val;5* TreeNode left;6...
回到顶部 思路 利用递归,每遍历一层时分别用两个变量记录左、右孩子结点的最长路径,通过相加更新最大值。最终得到结果。 回到顶部 代码 publicclassSolution{intmax=0;publicintdiameterOfBinaryTree(TreeNode root){ maxDepth(root);returnmax; }privateintmaxDepth(TreeNode root){if(root ==null)return0;intleft...