计算树的深度和后代

发布于 2024-08-31 11:48:17 字数 179 浏览 2 评论 0原文

你们能帮我用算法来做这些事情吗?我实现了前序、中序和后序,并且提示我使用这些顺序之一遍历树。我使用 dotty 来标记(或“访问”)节点。

深度是从根到底部叶子的边数,所以每次移动时,深度都会加1?类似的事情?

不知道后代的算法。他们询问特定节点自身下的节点数量。

顺便说一句,这些都是普通的树。

Can you guys help me with the algorithm to do these things? I have preorder, inorder, and postorder implemented, and I am given the hint to traverse the tree with one of these orders. I am using dotty to label (or "visit") the nodes.

Depth is the number of edges from the root to the bottom leaf, so everytime I move, I add +1 to the depth? Something like that?

No idea about the algorithm for descendants. They are asking about the number of nodes a specific node has under itself.

These are normal trees btw.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情栀口红 2024-09-07 11:48:17

这是家庭作业的问题吗?我的回答假设这是为了家庭作业。

树是一种递归数据结构,因此对其进行操作的算法通常是递归的。递归算法需要一个基本情况和一个归纳情况。对于树,基本情况是您访问叶节点(即没有子节点的节点)时所做的操作。归纳情况是当您访问内部节点(即具有至少一个子节点的节点)时您所做的事情。

用于计算深度(或树的“高度”):

  • 基本情况:没有子节点的节点的深度是多少?
  • 归纳案例:假设您拥有所有子节点的深度(可能不同),那么您正在访问的当前节点的深度是多少?

用于计算后代计数:

  • 基本情况:没有子节点的节点有多少个后代?
  • 归纳案例:假设您知道所有子节点的后代计数,那么您正在访问的当前节点的后代计数是多少?

我鼓励您提出澄清问题。

Is this a question for homework? My answer assumes it is for homework.

Trees are a recursive data structure, so the algorithms that operate on them will often be recursive. Recursive algorithms need a base case and an inductive case. For trees, the base case will be what you do when you are visiting a leaf node (i.e. a node without children). The inductive case will be what you do when you are visiting an internal node (i.e. a node with at least one child).

For calculating depth (or "height" of the tree):

  • Base case: What is the depth of a node without children?
  • Inductive case: Given that you have the depths of all of your children (which could be different), what is the depth of the current node you're visiting?

For calculating descendant count:

  • Base case: How many descendants does a node without children have?
  • Inductive case: Given that you know the descendant count of all of your children, what is the descendant count of the current node you're visiting?

I encourage you to ask clarifying questions.

靑春怀旧 2024-09-07 11:48:17
depth(tree) = 1+ max(depth(tree.left), depth(tree.right));

descendants(tree) = descendants(tree.left) + descendants(tree.right);

对于任一情况,为空指针返回 0 都会结束递归。

depth(tree) = 1+ max(depth(tree.left), depth(tree.right));

descendants(tree) = descendants(tree.left) + descendants(tree.right);

For either, returning 0 for a null pointer would end the recursion.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文