LeetCode - Easy - 543. Diameter of Binary Tree

r囧r小猫 2022-10-18 01:52 306阅读 0赞

Topic

  • Tree

Description

https://leetcode.com/problems/diameter-of-binary-tree/

Given the root of a binary tree, return 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.

The length of a path between two nodes is represented by the number of edges between them.

Example 1:

a20b6db60ec326cb2d4e4c28ea3f7835.png

  1. Input: root = [1,2,3,4,5]
  2. Output: 3
  3. Explanation: 3is the length of the path [4,2,1,3] or [5,2,1,3].

Example 2:

  1. Input: root = [1,2]
  2. Output: 1

Constraints:

  • The number of nodes in the tree is in the range [ 1 , 1 0 4 ] [1, 10^4] [1,104].
  • − 100 < = N o d e . v a l < = 100 -100 <= Node.val <= 100 −100<=Node.val<=100

Analysis

用到二叉树后序遍历模式。

Submission

  1. public class DiameterOfBinaryTree {
  2. public int diameterOfBinaryTree(TreeNode root) {
  3. int[] max = { 0};
  4. diameterOfBinaryTree(root, max);
  5. return max[0];
  6. }
  7. private int diameterOfBinaryTree(TreeNode node, int[] max) {
  8. if(node == null) return 0;
  9. int left = 0, right = 0;
  10. if(node.left != null)
  11. left = diameterOfBinaryTree(node.left, max) + 1;
  12. if(node.right != null)
  13. right = diameterOfBinaryTree(node.right, max) + 1;
  14. max[0] = Math.max(max[0], left + right);
  15. return Math.max(left, right);
  16. }
  17. }

Test

  1. import static org.junit.Assert.*;
  2. import org.junit.Test;
  3. import com.lun.util.BinaryTree;
  4. public class DiameterOfBinaryTreeTest {
  5. @Test
  6. public void test() {
  7. DiameterOfBinaryTree obj = new DiameterOfBinaryTree();
  8. assertEquals(3, obj.diameterOfBinaryTree(BinaryTree.integers2BinaryTree(1, 2, 3, 4, 5)));
  9. assertEquals(1, obj.diameterOfBinaryTree(BinaryTree.integers2BinaryTree(1, 2)));
  10. assertEquals(8, obj.diameterOfBinaryTree(BinaryTree.integers2BinaryTree(4,-7,-3,null,null,//
  11. -9,-3,9,-7,-4,null,6,null,-6,-6,null,null,0,6,5,null,9,null,null,-1,-4,null,null,null,-2)));
  12. }
  13. }

发表评论

表情:
评论列表 (有 0 条评论,306人围观)

还没有评论,来说两句吧...

相关阅读