2023年6月22日发(作者:)
⼆叉树任意两个节点间的最⼤距离(Java,LeetCode543⼆叉树的直径递归)⽂章⽬录题⽬给定⼀棵⼆叉树,你需要计算它的直径长度。⼀棵⼆叉树的直径长度是任意两个结点路径长度中的最⼤值。这条路径可能穿过也可能不穿过根结点⽰例给定⼆叉树: 1 / 2 3 /
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。注意:两结点之间的路径长度是以它们之间边的数⽬表⽰。代码思路:使⽤递归的⽅法,⽤⼀个全局变量max保存最⼤距离(⼀开始没写出来是因为把⾃⼰绕进去了,重点就在于,递归的时候,更新max⽤leftMax+rightMax,⽽返回leftMax和rightMax的较⼤值)/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { int max = 0; public int diameterOfBinaryTree(TreeNode root) { getMax(root); return max; } public int getMax(TreeNode node){ if(node == null){ return 0; } int leftMax = 0; int rightMax = 0; if( != null){ leftMax = getMax(); } if( != null){ rightMax = getMax(); } max = (leftMax + rightMax, max); return (leftMax, rightMax) + 1; }}
发布者:admin,转转请注明出处:http://www.yc00.com/news/1687384424a6051.html
评论列表(0条)