gpt4 book ai didi

algorithm - 二叉树中节点之间的距离?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:48:08 25 4
gpt4 key购买 nike

这一定是递归算法

dis(tree, x, y) <--函数调用x & y 是节点

每次递归调用返回 (dx, dy, dxy)dx 是 x 的深度dy 是 y 的深度dxy是彼此之间的距离

我正在考虑使用最低共同祖先,但这不适合这种格式(没有全局变量)。

最佳答案

This must be a recursive algorithm

我假设你的意思是作为对你想要的答案的限制(有迭代解决方案)。递归(函数式)解决方案如下:

dis(tree, x, x) = 0

dis(tree, x, NULL) = INF
dis(tree, NULL, x) = INF

dis(tree, x, y) = min(dis(tree, parent(x), y)+1, dis(tree, x, parent(y))+1)

关于algorithm - 二叉树中节点之间的距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11091203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com