今�Hの国の呵呵君: [Algorithm]Get Max Distance in Binary Tree
Distance定义为从一个节点到另一个节点经过的edge的数量,这一题其实跟max sum in bianry tree类似,返回左右子树的最深距离,然后相加看要不要更新返回值,然后去左和右的最大值加一return
private int dis = 0;
public int getMaxDistance(TreeNode root) {
getDistance(root);
return dis;
}
private int getDistance(TreeNode root) {
if(root == null)
return 0;
int left = getDistance(root.left);
int right = getDistance(root.right);
if(left + right > dis)
dis = left + right;
return left >= right? left + 1: right + 1;
}
Read full article from 今�Hの国の呵呵君: [Algorithm]Get Max Distance in Binary Tree
Distance定义为从一个节点到另一个节点经过的edge的数量,这一题其实跟max sum in bianry tree类似,返回左右子树的最深距离,然后相加看要不要更新返回值,然后去左和右的最大值加一return
private int dis = 0;
public int getMaxDistance(TreeNode root) {
getDistance(root);
return dis;
}
private int getDistance(TreeNode root) {
if(root == null)
return 0;
int left = getDistance(root.left);
int right = getDistance(root.right);
if(left + right > dis)
dis = left + right;
return left >= right? left + 1: right + 1;
}
Read full article from 今�Hの国の呵呵君: [Algorithm]Get Max Distance in Binary Tree