Validate Binary Search Tree

Validate Binary Search Tree.png

解題思路 :

test case 很賊會(huì)使用 INT_MAX 或是 INT_MIN 來(lái)測(cè)試 所以在 solution 1 的方法中 使用的邊界改成 LLONG_MIN 跟 LLONG_MAX 來(lái)避免超過(guò)極值的問(wèn)題 基本就是設(shè)定上下邊界遞歸的方式檢查左右子節(jié)點(diǎn) 如果真的忘記還可以用最後一招 inorder traversal 一次整棵樹(shù) 把數(shù)值存入 vector 然後掃過(guò)整個(gè) vector 看看是否有後面的值大於等於前面的狀況 有就代表不是 BST

C++ code :

<pre><code>
//solution 1
/**

  • Definition of TreeNode:
  • class TreeNode {
  • public:
  • int val;
    
  • TreeNode *left, *right;
    
  • TreeNode(int val) {
    
  •     this->val = val;
    
  •     this->left = this->right = NULL;
    
  • }
    
  • }
    */

class Solution {

public:

/**
 * @param root: The root of binary tree.
 * @return: True if the binary tree is BST, or false
 */
bool helper(TreeNode *root, long long min, long long max) {
    if (root == NULL) return true;
    if (root->val <= min || root->val >= max) return false;
    return helper(root->left, min, root->val) && helper(root->right, root->val, max);
}

bool isValidBST(TreeNode *root) {
    if (root == NULL) return true;
    return helper(root, LLONG_MIN, LLONG_MAX);
}

};

//solution 2

/**

  • Definition of TreeNode:
  • class TreeNode {
  • public:
  • int val;
    
  • TreeNode *left, *right;
    
  • TreeNode(int val) {
    
  •     this->val = val;
    
  •     this->left = this->right = NULL;
    
  • }
    
  • }
    */

void inorder(TreeNode *root, vector<int> &v)
{

if(root != nullptr)
{
    inorder(root->left, v);
    v.emplace_back(root->val);
    inorder(root->right, v);
}

}

class Solution {

public:

/**
 * @param root: The root of binary tree.
 * @return: True if the binary tree is BST, or false
 */
bool isValidBST(TreeNode *root) {
    // write your code here
   if(root == nullptr) return true;
   vector<int> treeValue;
   inorder(root, treeValue);
   for(int i = 0; i < treeValue.size() - 1; i++)
   {
       if(treeValue[i] >= treeValue[i+1]) return false;
   }
   return true;
}

};

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容