【发布时间】:2015-11-21 10:30:17
【问题描述】:
我正在尝试编写一个方法,如果二叉树已满(每个节点有 2 个子节点或没有子节点)将返回 true,否则返回 false。这在某些时候有效,但不是全部。关于我哪里出错的任何建议?
public static void testNum4()
{
System.out.println("How many nodes do you want in your tree?");
int num=sc.nextInt();
//TreeNode<Integer> root = TreeUtil.createBalancedNumberTree(num); Use to test for a balanced tree
TreeNode<Integer> root = TreeUtil.createIntegerTree(num);
TreeUtil.displayTreeInWindow(root);
System.out.println(isFull(root));
TreeUtil.displayTreeInWindow (root);
}
public static boolean isFull(TreeNode<Integer> root) {
// pre: root of tree, 0 or more nodes
// post: returns true if the input tree is a full tree; false otherwise
if (root!=null) {
if ((root.getLeft() != null && root.getRight() != null) || (root.getRight() == null && root.getLeft() == null))
{
return true;
}
else if (root.getLeft()!=null)
{
isFull(root.getLeft());
}
else if (root.getRight()!=null)
{
isFull(root.getRight());
}
else
return false;
}
return false;
}
【问题讨论】:
-
你的问题能说清楚吗?
-
如果树是完整的,我将永远正确。但是,如果它不完整,有时我会得到 true(这是错误的),有时会得到 false。
-
第一个
if条件也不正确。如果一个节点(根)有 2 个子节点,则返回 true 而不递归地检查它们