也可以在迭代每一个node的时候,记录下其diameter,ans就是所有node diameter最大值: #Definition for a binary tree node.#class TreeNode(object):#def __init__(self, x):#self.val = x#self.left = None#self.right = NoneclassSolution(object):defdiameterOfBinaryTree(self, root):""":type root:...
returnmax(res, max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right))); } intdepthOfNode(TreeNode *node) { if(!node)return0; returnmax(depthOfNode(node->left), depthOfNode(node->right)) + 1; } }; 类似题目: [LeetCode] 104. Maximum Depth of Binary Tree 二叉树的...
力扣543.二叉树的直径(点击查看题目) 力扣leetcode-cn.com/problems/diameter-of-binary-tree/ 题目描述 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。 示例: 给定二叉树 1 / \ 2 3 / \ 4 5 返回3, 它...
543. Diameter of Binary Tree(二叉树的最长直径) 给定二叉树,您需要计算树直径的长度。二叉树的直径是一棵树中任何两个节点之间的最长路径的长度。此路径可能会也可能不会通过根。 思路: 要计算二叉树的最长直径,肯定需要遍历树,而最长直径肯定有一个相对的root节点,所以可以后序遍历了,每到达一个节点就要计算...
classSolution{intdiameter=;publicintdiameterOfBinaryTree(TreeNode root){ depth(root);return diameter;}publicintdepth(TreeNode node){if(node ==null)return;intleftLen= depth(node.left);// node左子树最大深度intrightLen= depth(node.right);// node右子树最大深度 diameter =Math.max(diameter...
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 tree is the length of thelongestpath between any two nodes in a tree. This path may or may not pass through the root....
solution2: 一个递归函数。 只需要用一个递归函数就可以了,可以在求深度的递归函数中顺便就把直径算出来,而且貌似不用进行优化也能accept。 solution3: 优化版本。 参考 1. Leetcode_easy_543. Diameter of Binary Tree; 2. Grandyang; 完...
AcWing-Leetcode 暑期刷题打卡训练营第5期 LeetCode_543_Diameter of Binary Tree 添加我们的acwing微信小助⼿ 微信号:acwinghelper 或者加入QQ群:728297306 即可与其他刷题同学一起互动哦~ AcWing 算法提高班开…
243 1 8:21 App LeetCode力扣刷题实录:[简单]543. 二叉树的直径 32 -- 4:49 App NOIP2010普及组 第24题 220 -- 10:21 App leetcode力扣刷题543 java 二叉树的直径 0ms 100%时间最优解 Diameter of Binary Tree 9945 73 13:14 App 【LeetCode 10. 正则表达式匹配】 每天一题刷起来!C++ 年薪...
class Solution { private int max = 0; public int diameterOfBinaryTree(TreeNode root) { maxDepth(root); return max; } private int maxDepth(TreeNode root){ if(root == null) return 0; int l = maxDepth(root.left); int r = maxDepth(root.right); max = Math....