这里写自定义目录标题
二叉树节点间的最大距离问题
思路
求二叉树两节点间的最大距离(可能过根节点,也可能不过)
1.有可能跨越了根节点 连接了左右子树,所以最大值为左右子树高度加1
2.有可能最大距离就在左子树内部 ,没有跨越根节点
3.有可能最大距离就在右子树内部 ,没有跨越根节点
链接:https://www.nowcoder.com/questionTerminal/88331be6da0d40749b068586dc0a2a8b?orderByHotValue=1&questionTypes=000100&mutiTagIds=583&page=2&onlyReference=false
来源:牛客网
int maxDistance(TreeNode root){
if (root == null){
return 0 ;
}
return Math.max(height(root.left)+height(root.right)+1 ,
Math.max(maxDistance(root.left) , maxDistance(root.right))) ;
}
int height(TreeNode root){
if (root == null){
return 0 ;
}
return Math.max(height(root.left) , height(root.right))+1 ;
}