int max=Integer.MIN_VALUE;
int maxHeightSum(TreeNode root) {
if (root == null) return 0;
int maxL = Math.max(maxHeightSum(root.left), 0);
int maxR = Math.max(maxHeightSum(root.right), 0);
//這個是關鍵,採用後根順序遍歷二叉樹,max保存不含根節點的最大路徑。在這個時候需要刷新
max = Math.max(maxL + maxR + root.val, max);
//實際返回的是最大有效深度
return Math.max(maxL, maxR) + root.val;
}
public int maxPathSum(TreeNode root) {
if (root == null)
return 0;
maxHeightSum(root);
return max;
}
求二叉樹最遠距離
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.