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);
}
};