力扣543.二叉树的直径(点击查看题目) 力扣leetcode-cn.com/problems/diameter-of-binary-tree/ 题目描述 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。 示例: 给定二叉树 1 / \ 2 3 /
也可以在迭代每一个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 二叉树的...
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...
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...
第一反映是递归,假设root的左子树以及右子树的diameterOfBinaryTree已经求解出来,那么我们只需要判断一种情况即可,即diameterOfBinaryTree的path并没有经过根节点的情况。 也就是说,path存在于root的左子树或者右子树中。遇到这种情况,只有可能是左子树的深度+右子树的深度 < 左子树的diameter或者右子树的diameter。所以...
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....
543Diameter of Binary TreePythonJavaDFS with O(1) for max answer 547Friend CirclesPythonJava1. DFS, O(n^2) and O(1) 2. BFS, O(n^2) and O(1) 3. Union-find, O(n^2) and O(n) 557Reverse Words in a String IIIPythonJavaString handle: Split with space than reverse word, O(n...