Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode() {}
- * TreeNode(int val) { this.val = val; }
- * TreeNode(int val, TreeNode left, TreeNode right) {
- * this.val = val;
- * this.left = left;
- * this.right = right;
- * }
- * }
- */
- class Solution {
- int maxDiametar = 0;
- public int diameterOfBinaryTree(TreeNode root) {
- if (root == null) {
- return 0;
- }
- preorder(root);
- return maxDiametar;
- }
- public void preorder(TreeNode root) {
- if (root == null) {
- return;
- }
- maxDiametar = (int)Math.max(maxDiametar,maxDistance(root.left) + maxDistance(root.right));
- preorder(root.right);
- preorder(root.left);
- }
- public int maxDistance(TreeNode root) {
- if (root == null) {
- return 0;
- }
- int left = maxDistance(root.left);
- int right = maxDistance(root.right);
- return (int)Math.max(left,right) + 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement