尝试检查Tree是否是二进制搜索树

时间:2013-12-12 15:35:42

标签: algorithm tree binary-tree binary-search-tree

首先,我根据Level order(又名广度优先)遍历将树插入数组中。 现在我检查数组

 For i=1 to Len(Array) do:
         IF 2*i smaller than Len(Array) then:
            IF Array[i] smaller than Array[2i] OR Array[i] larger than  Array[2i+1] then:
                 Return false
         Else if 2*I larger than Len(Array) then 
            Return True

但我的问题是算法仅在树是完整的二叉树时工作

2 个答案:

答案 0 :(得分:0)

作为提示,当且仅当树的顺序遍历按排序顺序列出键时,二叉树才是二叉搜索树。尝试从逐级遍历切换到顺序遍历并进行适当的修改。

希望这有帮助!

答案 1 :(得分:0)

清晰,简洁,高效的代码:如果你真正了解这种现象,递归很酷。我们的想法是验证树的每个节点,使其始终在最小值和最大值之间。以 Integer.MIN_VALUE Integer.MAX_VALUE 作为min和max的初始输入开始。

public boolean isBinarySearch(Node root, int min, int max) {

    if (root == null)
        return true;

    return ((min <= root.val && root.val <= max) && (isBinarySearch(
            root.left, min, root.val) && isBinarySearch(root.right,
            root.val, max)));
} 

你也可以尝试一下。

class Node {

public Node left;
public Node right;
public int val;

public Node(int val) {
    this.val = val;
 }
}

现在这样做。

    Node root2 = new Node(12);
    root2.left = new Node(7);
    root2.left.left = new Node(4);
    root2.left.right = new Node(11);
    root2.right = new Node(16);
    root2.right.left = new Node(14);
    root2.right.right = new Node(18);
    root2.right.right.left = new Node(17);

    System.out
            .println("IsBinary="
                    + wc.isBinarySearch(root2, Integer.MIN_VALUE,
                            Integer.MAX_VALUE));
}
相关问题