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 ...
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...
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...
* 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...
开始耍小聪明啦,getMax是求得深度最大值。我们在diameterOfbinaryTree中不断求得左右子树的直径,相加,并且递归,即可获得最大值 /** * Definition for a binary tree node. * struct TreeNode { * int val; * T
* Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */classSolution{public:intMax =0;intdfs(TreeNode* root){if(root ==nullptr)return0;intd1 =0;intd2 =...
回到顶部 思路 利用递归,每遍历一层时分别用两个变量记录左、右孩子结点的最长路径,通过相加更新最大值。最终得到结果。 回到顶部 代码 publicclassSolution{intmax=0;publicintdiameterOfBinaryTree(TreeNode root){ maxDepth(root);returnmax; }privateintmaxDepth(TreeNode root){if(root ==null)return0;intleft...
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 the longestpath between any two nodes in a tree. This path may or m......
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...