首页 > 其他分享 >leetcode-543二叉树直径

leetcode-543二叉树直径

时间:2023-02-02 18:32:23浏览次数:46  
标签:right TreeNode val int max 543 二叉树 root leetcode

//leetcode submit region begin(Prohibit modification and deletion)

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {

int max = 0;

public int diameterOfBinaryTree(TreeNode root) {

maxDepth(root);
reutrn max;
}

int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}

int leftMaxDepth = maxDepth(root.left);
int rightMaxDepth = maxDepth(root.right);

max = Math.max(max, leftMaxDepth + rightMaxDepth);
return Math.max(rightMaxDepth, leftMaxDepth) + 1;
}
}
//leetcode submit region end(Prohibit modification and deletion)

标签:right,TreeNode,val,int,max,543,二叉树,root,leetcode
From: https://blog.51cto.com/u_12550160/6033835

相关文章

  • #yyds干货盘点# LeetCode面试题:两数相加
    1.简述:给你两个 非空的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。请你将两个数相加,并以相同形式返回一个表......
  • #yyds干货盘点# LeetCode程序员面试金典:幂集
    题目:幂集。编写一种方法,返回某集合的所有子集。集合中不包含重复的元素。说明:解集不能包含重复的子集。示例:输入:nums=[1,2,3]输出:[ [3], [1], [2], [1,2,3],......
  • LeetCode.150 逆波兰表达式求值
    1.题目给你一个字符串数组 ​​tokens​​​ ,表示一个根据 ​​逆波兰表示法​​ 表示的算术表达式。请你计算该表达式。返回一个表示表达式值的整数。2.代码classSolu......
  • [LeetCode]Minimum Path Sum
    QuestionGivenamxngridfilledwithnon-negativenumbers,findapathfromtoplefttobottomrightwhichminimizesthesumofallnumbersalongitspath.N......
  • [LeetCode]Unique Paths
    QuestionArobotislocatedatthetop-leftcornerofamxngrid(marked‘Start’inthediagrambelow).Therobotcanonlymoveeitherdownorrightatany......
  • [LeetCode]Permutation Sequence
    QuestionTheset[1,2,3,…,n]containsatotalofn!uniquepermutations.Bylistingandlabelingallofthepermutationsinorder,Wegetthefollowingsequen......
  • [LeetCode]Length of Last Word
    QuestionGivenastringsconsistsofupper/lower-casealphabetsandemptyspacecharacters​​​''​​,returnthelengthoflastwordinthestring.Ifthe......
  • [LeetCode]Insert Interval
    QuestionGivenasetofnon-overlappingintervals,insertanewintervalintotheintervals(mergeifnecessary).Youmayassumethattheintervalswereinitial......
  • [LeetCode]Merge Intervals
    Question本题难度Hard。排序+双指针【复杂度】时间O(Nlog(N))空间O(N)【思路】先按照每个元素的​​​start​​​从小到大进行排序。然后利用双指针法,设置区间​​......
  • [LeetCode]Maximum Subarray
    QuestionFindthecontiguoussubarraywithinanarray(containingatleastonenumber)whichhasthelargestsum.Forexample,giventhearray[-2,1,-3,4,-1,2,1......