二叉排序樹的判斷(hackerrank) java

簡單介紹下二叉樹排序樹:

  1. The value of every node in a node’s left subtree is less than the data value of that node.
  2. The value of every node in a node’s right subtree is greater than the data value of that node.

    之前在網上看到很多人寫的,只想說你們測試過嗎?你們測試了幾個案例?

    下面開始寫我在hackerrank測試滿分的源碼:

boolean checkBST(Node root) {
    return checkBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE); 
}

boolean checkBST(Node root, int min, int max) {
    if (root == null) return true; 

    if (root.data <= min || root.data >= max)
        return false;

    if (!checkBST(root.left, min, root.data) || !checkBST(root.right, root.data, max))
        return false;

    return true;
}

重載是爲了支持更多方式使用,根本還是第二個方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章