Advertisement
Kame3

Diameter of Binary Tree

May 25th, 2021
1,688
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. Given the root of a binary tree, return the length of the diameter of the tree.
  2.  
  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.  
  5. The length of a path between two nodes is represented by the number of edges between them.
  6.  
  7.  
  8.  
  9. /**
  10.  * Definition for a binary tree node.
  11.  * public class TreeNode {
  12.  *     int val;
  13.  *     TreeNode left;
  14.  *     TreeNode right;
  15.  *     TreeNode() {}
  16.  *     TreeNode(int val) { this.val = val; }
  17.  *     TreeNode(int val, TreeNode left, TreeNode right) {
  18.  *         this.val = val;
  19.  *         this.left = left;
  20.  *         this.right = right;
  21.  *     }
  22.  * }
  23.  */
  24. class Solution {
  25.     int maxDiametar = 0;
  26.    
  27.     public int diameterOfBinaryTree(TreeNode root) {    
  28.         if (root == null) {
  29.             return 0;
  30.         }
  31.        
  32.         preorder(root);
  33.        
  34.         return maxDiametar;
  35.     }
  36.    
  37.     public void preorder(TreeNode root) {
  38.         if (root == null) {
  39.             return;
  40.         }
  41.        
  42.         maxDiametar = (int)Math.max(maxDiametar,maxDistance(root.left) + maxDistance(root.right));
  43.        
  44.         preorder(root.right);
  45.         preorder(root.left);
  46.     }
  47.    
  48.     public int maxDistance(TreeNode root) {
  49.         if (root == null) {
  50.             return 0;
  51.         }
  52.        
  53.         int left = maxDistance(root.left);
  54.         int right = maxDistance(root.right);
  55.        
  56.         return (int)Math.max(left,right) + 1;
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement