cuốn sách gpt4 ai đã làm

Lấy khoảng cách từ gốc đến nút của một giá trị cho trước trong cây nhị phân: Độ chính xác của thuật toán

In lại Tác giả: Taklimakan 更新时间:2023-11-03 04:33:40 26 4
mua khóa gpt4 Nike

đây là mã của tôi

 public int getDist(Node root, int value)
{
if (root == null && value !=0)
return -1;//
if(root.value == value)// we have a match
return 0;
if(root.getLeft()!=null)
int left =1+ getDist(root.getLeft(),value);
int right = 1+getDist(root.getRight(),value);
if(left ==-1 && right== -1)
return -1;//not found
return Math.max(left,right);
}

对于上述方法的正确性或任何优化的任何反馈,我将不胜感激。

câu trả lời hay nhất

就目前而言,您的代码不会按预期工作。另一方面考虑一下:

public int getDist(Node root, int value) {

// value is never in an empty subtree
if (root == null)
return -1;

// found value, distance from root is 0
if(root.value == value)
return 0;

// find distance from root of left subtree
int left = getDist(root.getLeft(),value);

// find distance from root of right subtree
int right = getDist(root.getRight(),value);

// value not found in either subtree
if(left == -1 && right == -1)
return -1;

// if the value was found,
// return the distance from the root of the subtree + 1
return 1 + Math.max(left,right);
}

我所做的更改是删除一些多余的检查并在检查“值不在任一子树中”之后移动 +1。其效果如下:如果递归发现该值不在子树中,则 trở lại 语句会将值 -1 一直波纹到子树的根而不改变它,保持信息“值不在这里”不变。如果在至少一个子树中找到该值,则 bên tráiright 不可能都是 -1,因此检查将失败,最后的 trở lại 语句将返回预期值。

关于algorithm - 获取二叉树中给定值的根到节点的距离 : Algorithm correctness,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22585740/

26 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress