LeetCode543 Diameter of binary tree
the defination of diameter of binary tree is the longest path(the edge number instead of the nodes number) between any two nodes in a tree.

idea:
this is the kind of problem that I have no single clue
class Solution {
int maxLevel = 0;
public int diameterOfBinaryTree(TreeNode root) {
deepest(root);
return maxLevel;
}
private int deepest(TreeNode root) { //this function means deepest of this tree
if (root == null) {
return 0;//level 0
}
int left = deepest(root.left); //the deepest of left subtree
int right = deepest(root.right); //the deepest of right subtree
maxLevel = Math.max(maxLevel, left + right); //update maxLevel, we always want a global max depth
return Math.max(left, right) + 1; //this is the depth with root is current root
}
}

浙公网安备 33010602011771号