|
| 1 | +/* |
| 2 | +Given the root of a binary tree, return the length of the diameter of the tree. |
| 3 | +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. |
| 4 | +The length of a path between two nodes is represented by the number of edges between them. |
| 5 | +
|
| 6 | +Example 1: |
| 7 | +Input: root = [1,2,3,4,5] |
| 8 | +Output: 3 |
| 9 | +Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. |
| 10 | + */ |
| 11 | +import java.util.ArrayList; |
| 12 | +import java.util.LinkedList; |
| 13 | +import java.util.List; |
| 14 | +import java.util.Queue; |
| 15 | + |
| 16 | +public class DiameterOfBinaryTree { |
| 17 | + public static void main(String[] args) { |
| 18 | + TreeNode root=new TreeNode(1); |
| 19 | + root.left=new TreeNode(2); |
| 20 | + root.right=new TreeNode(3); |
| 21 | + root.left.left=new TreeNode(4); |
| 22 | + int ans = diameterOfBinaryTree(root); |
| 23 | + System.out.println(ans); |
| 24 | + } |
| 25 | + public static int diameterOfBinaryTree(TreeNode root) { |
| 26 | + List<Integer> result = new ArrayList<>(); |
| 27 | + if (root == null) { |
| 28 | + return 0; |
| 29 | + } |
| 30 | + Queue<TreeNode> queue = new LinkedList<>(); |
| 31 | + queue.offer(root); |
| 32 | + |
| 33 | + while (!queue.isEmpty()) { |
| 34 | + int levelSize = queue.size(); |
| 35 | + for (int i = 0; i < levelSize; i++) { |
| 36 | + TreeNode cur = queue.poll(); |
| 37 | + |
| 38 | + int leftDepth = maxDepth(cur.left); |
| 39 | + int rightDepth = maxDepth(cur.right); |
| 40 | + result.add(leftDepth + rightDepth); |
| 41 | + |
| 42 | + if (cur.left != null) { |
| 43 | + queue.offer(cur.left); |
| 44 | + } |
| 45 | + if (cur.right != null) { |
| 46 | + queue.offer(cur.right); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + int max = Integer.MIN_VALUE; |
| 52 | + for (int num : result) { |
| 53 | + if (num > max) { |
| 54 | + max = num; |
| 55 | + } |
| 56 | + } |
| 57 | + return max; |
| 58 | + } |
| 59 | + |
| 60 | + public static int maxDepth(TreeNode root) { |
| 61 | + if (root == null) { |
| 62 | + return 0; |
| 63 | + } |
| 64 | + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); |
| 65 | + } |
| 66 | +} |
0 commit comments