【发布时间】:2021-10-06 14:23:01
【问题描述】:
第二个代码工作正常,而第一个代码每次都返回 0。为什么会这样?
在第一个代码 sn-p 中,我通过引用“height”方法传递“ans”变量,该方法假设修改传递的“ans”变量。
class Solution {
public int diameterOfBinaryTree(TreeNode root) {
int ans=0;
if(root==null)return 0;
height(root,ans);
return ans;
}
public int height(TreeNode root,int ans){
if(root==null)return 0;
int L=height(root.left,ans);
int R=height(root.right,ans);
ans = Math.max(ans,L+R);
return 1+Math.max(L,R);
}
}
下面的代码可以正常工作。
class Solution {
int ans=0;
public int diameterOfBinaryTree(TreeNode root) {
if(root==null )return 0;
height(root);
return ans;
}
public int height(TreeNode root){
if(root==null)return 0;
int L=height(root.left);
int R=height(root.right);
ans=Math.max(ans,L+R);
return 1+Math.max(L,R);
}
}
【问题讨论】:
标签: java optimization binary-tree binary-search-tree