Moment For Technology

Question 21: The diameter of the binary tree

Posted on Aug. 10, 2023, 1:29 p.m. by 余雅琪
Category: LeetCode Personal Problem Solving Summary Tag: LeetCode Personal Problem Solving Summary

Diameter points of a binary tree: what the root node needs to do is to add the height of the left subtree and the right subtree, and then add 1 to get the diameter length of the node. An intermediate variable Max is used to record the longest diameter, and the final Max is the result. Calculate the diameter: 1. Obtain the height of the left subtree; 2. Obtain the height of the right subtree; 3.

class Solution { int max = Integer.MIN_VALUE; public int diameterOfBinaryTree(TreeNode root) { height(root); return max - 1; } public int height(TreeNode root){ if(root == null) return 0; int left = height(root.left); int right = height(root.right); max = Math.max(left + right + 1,max); return Math.max(left,right) + 1; }}
About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.