题目:
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.
- A single node tree is a BST
An example:
2
/
1 4
/
3 5
The above binary tree is serialized as {2,1,4,#,#,3,5}
(in level order).
题解:
按照定义,二叉搜索树的中序遍历是升序序列
Solution 1 ()
class Solution { public: /** * @param root: The root of binary tree. * @return: True if the binary tree is BST, or false */ bool isValidBST(TreeNode *root) { TreeNode *prev = nullptr; return validate(root, prev); } bool validate(TreeNode *node, TreeNode* &prev) { if (node == nullptr) { return true; } if (!validate(node->left,prev)) { return false; } if (prev != nullptr && prev->val >= node->val) { return false; } prev = node; return validate(node->right, prev); } };
分治法 from here
Solution 2 ()
class ResultType { public: bool isBST; TreeNode *maxNode, *minNode; ResultType(): isBST(true), maxNode(nullptr), minNode(nullptr) {} }; class Solution { public: bool isValidBST(TreeNode *root) { ResultType result = helper(root); return result.isBST; } ResultType helper(TreeNode *root) { ResultType result; if (root == nullptr) { return result; } ResultType left = helper(root->left); ResultType right = helper(root->right); if (!left.isBST || !right.isBST) { result.isBST = false; return result; } if (left.maxNode != nullptr && left.maxNode->val >= root->val) { result.isBST = false; return result; } if (right.minNode != nullptr && right.minNode->val <= root->val) { result.isBST = false; return result; } result.isBST = true; result.minNode = left.minNode == nullptr ? root : left.minNode; result.maxNode = right.maxNode == nullptr ? root : right.maxNode; return result; } };