【发布时间】:2017-04-15 15:16:11
【问题描述】:
我正在尝试为树中的每一片叶子分配编号。
例如,如果我们有一棵有 6 片叶子的树,我希望叶子的数字从 0 到 5。
我不知道为什么我的代码不能很好地工作,我已经尝试了很多次,即使是递归方式,但似乎我错过了一些东西..
public class Node {
int index;
int id;
Node left;
Node right;
// Constructor and setters/getters.
public static void num(Node n) {
int ini=0;
if(n==null)
{
}
if(n.isLeaf())
{
n.index=ini;
ini++;
}
if(!n.isLeaf())
{
num(n.getleft());
num(n.getRight());
}
}
我还想得到树上叶子的数量。
例如,我们的树看起来像
1
/ \
2 3
/ \ / \
6 9 8 10
/
4
public static int numberChild(Node n, int count)
{
if (n == null) {
return 0;
}
if (n.getleft() == null && n.getRight() == null) {
return 1 + count;
} else {
int lc = numberChild(n.getleft(), count);
int rc = numberChild(n.getRight(), lc);
return rc;
}
}
会给我错误的叶子数量,2 而不是 4!
有什么帮助吗?
【问题讨论】:
-
您的树是否以任何方式排序,您是否希望按任何顺序分配标签?
-
树没有排序,叶子是排序的,我们从左到右开始索引。这意味着我们需要一个反向波兰符号。
-
我在你的代码中看不到任何错误。可以试试调试器吗?
-
我没有得到关于“假设树不是二叉树”的部分。你的
Node有两个后代,left和right,这对我来说听起来像是一棵二叉树。 -
@OleV.V.有错误。对于上面绘制的树,叶子的数量应该是 4,我只得到 3。但是如果节点 6 有 2 个叶子,输出会是正确的,但是当我们有一个只有 1 个叶子的节点时,我会出错输出。我编辑了我的帖子,我只想说树没有排序,这意味着我们可以让右孩子 n.right 填充而 n.left 不填充。
标签: java recursion data-structures tree nodes