计算树的深度和后代
你们能帮我用算法来做这些事情吗?我实现了前序、中序和后序,并且提示我使用这些顺序之一遍历树。我使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是家庭作业的问题吗?我的回答假设这是为了家庭作业。
树是一种递归数据结构,因此对其进行操作的算法通常是递归的。递归算法需要一个基本情况和一个归纳情况。对于树,基本情况是您访问叶节点(即没有子节点的节点)时所做的操作。归纳情况是当您访问内部节点(即具有至少一个子节点的节点)时您所做的事情。
用于计算深度(或树的“高度”):
用于计算后代计数:
我鼓励您提出澄清问题。
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):
For calculating descendant count:
I encourage you to ask clarifying questions.
对于任一情况,为空指针返回 0 都会结束递归。
For either, returning 0 for a null pointer would end the recursion.