【LeetCode】- Validate Binary Search Tree

1、題目描述

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:

Input:
? 2
? / \
1 ? 3
Output: true

Example 2:
5
/ \
1 4
? / \
3 ? 6
Output: false

  • Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value is 5 but its right child's value is 4.

2、問(wèn)題描述:

  • 有效的二叉搜索樹(shù),左子樹(shù)的所有值小于根節(jié)點(diǎn),右子樹(shù)的所有結(jié)點(diǎn)值大于根節(jié)點(diǎn)。(記住是所有的哦),左右子樹(shù)也都是二叉搜索樹(shù)。

3、問(wèn)題關(guān)鍵:

  • 1.分別遞歸的求解左右子樹(shù)是否是二叉搜索樹(shù)。
  • 2.遞歸的時(shí)候需要更新,左右子樹(shù)的最大值和最小值。
  • 3.記住要使用引用變量,記錄最小值和最大值,值傳遞不可以。

4、C++代碼:

class Solution {
public:
    bool dfs(TreeNode* &root, int &maxv, int &minv) {//記得是引用傳遞。
        if (!root) return true;
        minv = maxv = root->val;
        if (root->left) {
            int nowmax, nowmin;
            if (!dfs(root->left, nowmax, nowmin)) return false;
            if (nowmax >= root->val) return false;//這個(gè)地方是可以大于maxv的,因?yàn)檫@個(gè)時(shí)候還么有更新maxv的值。
            minv = nowmin;//如果左子樹(shù)的是一個(gè)合法的,那么返回左邊的最小值,因?yàn)樽笞訕?shù)的最大值是小于當(dāng)前結(jié)點(diǎn)的值。
        }
        if (root->right) {
            int nowmax, nowmin;
            if (!dfs(root->right, nowmax, nowmin)) return false;
            if (nowmin <= root->val) return false;//這是小于等于root->val,因?yàn)樯厦鏁?huì)更新minv的值。
            maxv = nowmax;
        }
        return true;
    }
    bool isValidBST(TreeNode* root) {
        if (!root) return true;
        int maxv, minv; 
        return dfs(root, maxv, minv);
    }
};
?著作權(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)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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