验证二叉树中的所有数据条目是相同的

时间:2016-09-24 21:48:59

标签: java algorithm binary-tree

我使用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;
}

我试图通过这个来检查代码,但我不确定我是否正在充分检查所有节点(即叶子)。此外,我试图找出一种方法来攻击这个不递归或更高效的问题。任何帮助或建议将不胜感激。

2 个答案:

答案 0 :(得分:1)

没有充分检查所有节点。

问题是如果root.left非空,那么你永远不会检查root.right;所以这样的树:

     3
    / \
   3   4

将被误分类为仅包含目标。

更好的方法是写:

public static boolean allEqual(intBTNode root, int target)
{
    return root == null
        || root.data == target
           && allEqual(root.left, target)
           && allEqual(root.right, target);
}

如果你想出于某种原因想避免递归,你可以通过维护你已经“发现”的节点集合(通过访问他们的父节点)来实现这一点,但还没有真正“访问过”(通过检查他们的{ {1}}和孩子们),并不断从该集合中拉出节点,并访问它们,直到它为空:

data

(这实际上完全等同于递归版本,只是使用public static boolean allEqual(intBTNode root, int target) { List<intBTNode> nodesToVisit = new ArrayList<intBTNode>(); nodesToVisit.add(root); while (! nodesToVisit.isEmpty()) { intBTNode node = nodesToVisit.remove(nodesToVisit.size() - 1); if (node == null) continue; if (node.data != target) return false; nodesToVisit.add(node.left); nodesToVisit.add(node.right); } return true; } 作为堆栈而不是使用调用堆栈。)

答案 1 :(得分:0)

你应该替换

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;

return root.data == target && allEqual(root.left, target) && allEqual(root.right, target);

由于您当前的代码忽略了正确的子树(而且,空检查也是多余的,因为每次检查根是否为null)

至于避免递归,您可以使用不同的while循环,将当前节点的子节点推入堆栈(使用root初始化)并始终弹出第一个元素。 (当然,data == target