[LeetCode] Validate Binary Search Tree
2012-11-16 09:23
387 查看
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.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
The above binary tree is serialized as
递归判断,递归时传入两个参数,一个是左界,一个是右界,节点的值必须在两个界的中间,同时在判断做子树和右子树时更新左右界。
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.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5
The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}".
递归判断,递归时传入两个参数,一个是左界,一个是右界,节点的值必须在两个界的中间,同时在判断做子树和右子树时更新左右界。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool check(TreeNode *node, int leftVal, int rightVal) { if (node == NULL) return true; return leftVal < node->val && node->val < rightVal && check(node->left, leftVal, node->val) && check(node->right, node->val, rightVal); } bool isValidBST(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function return check(root, INT_MIN, INT_MAX); } };
相关文章推荐
- Java for LeetCode 098 Validate Binary Search Tree
- [leetcode 98] Validate Binary Search Tree
- Validate Binary Search Tree:from LeetCode
- [leetcode]98. Validate Binary Search Tree@Java解题报告
- Leetcode-98. Validate Binary Search Tree
- Validate Binary Search Tree [leetcode]
- LeetCode题解:Validate Binary Search Tree
- Validate Binary Search Tree_Leetcode
- Leetcode 98. Validate Binary Search Tree
- leetcode — validate-binary-search-tree
- LeetCode_Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree 解题报告
- LeetCode: Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- leetcode_Validate Binary Search Tree
- 【LeetCode】 ValidateBinarySearchTree
- LeetCode Validate Binary Search Tree
- LeetCode 98. Validate Binary Search Tree
- LEETCODE: Validate Binary Search Tree
- LeetCode 98: Validate Binary Search Tree