我使用Java进行二叉树(不是二叉搜索树)。我有类和实例变量声明:验证二叉树中所有的数据项都等于
class intBTNode
{
private int data;
private intBTNode left;
private intBTNode right;
我想要做的就是写一个返回true,只有树中的所有条目等于目标数,或者如果树是空的方法。 我写了下面的代码:
public static boolean allEqual(intBTNode root, int target)
{
if (root == null)
return true;
if (root.data == target && root.left != null)
return allEqual(root.left, target);
if (root.data == target && root.right != null)
return allEqual(root.right, target);
return false;
}
我想我的工作方式,通过这个来检查代码,但我不知道我充分检查所有节点(即叶)的。此外,我试图找出一种方法来攻击这个问题是不是递归或会更有效。任何帮助或建议,将不胜感激。