【LeetCode】98. Validate Binary Search Tree(C++)
阿新 • • 發佈:2018-12-16
地址:https://leetcode.com/problems/validate-binary-search-tree/
題目:
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
- Both the left and right subtrees must also be binary search trees.
Example 1:
Example 2:
理解:
判斷一個樹是不是二叉排序樹。
實現1:
採用中序遍歷的方式,得到的應該是一個有序序列,如果其中存在無序元素,就把標記修改,最後返回標記。
class Solution {
TreeNode* pre = nullptr;
bool valid = true;
public:
bool isValidBST(TreeNode* root) {
isValid(root);
return valid;
}
void isValid(TreeNode* root) {
if (!root) return;
isValid(root->left);
if (pre&&pre->val >= root->val) valid = false;
pre = root;
isValid(root->right);
}
};
實現2:
看了下別人的實現,使用從上到下的方式,標記這個結點上面的最大值和最小值,一旦不滿足就返回false,這樣比較快。
class Solution {
public:
bool isBalanced(TreeNode* curr, long minVal, long maxVal) {
if (!curr) return true;
long currVal = static_cast<long>(curr->val);
if (currVal > maxVal || currVal < minVal) return false;
return (isBalanced(curr->left, minVal, currVal - 1) &&
isBalanced(curr->right, currVal + 1, maxVal));
}
bool isValidBST(TreeNode* root) {
return isBalanced(root, LONG_MIN, LONG_MAX);
}
};