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 the node's key.
- Both the left and right subtrees must also be binary search trees.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
思路:根据题目要求,实现三个方面判断,左子树、右子树以及左子树小于根节点,右子树大于根节点
java代码:
- public boolean isValidBST(TreeNode root) {
- if(root==null) return true;
- if(root.left == null && root.right == null) return true;
- boolean flag = isValidBST(root.left) && isValidBST(root.right);
- if(flag==false) return false;
- TreeNode left = root.left;
- if(left!=null) {
- while(left.right!=null) {
- left = left.right;
- }
- flag &= (left.val<root.val);
- }
- TreeNode right = root.right;
- if(right!=null) {
- while(right.left!=null) {
- right = right.left;
- }
- flag &= (right.val > root.val);
- }
- return flag;
- }
C++代码:
- bool isValidBST(TreeNode *root) {
- bool lflag=false;
- bool rflag=false;
- if(root==NULL || (root->left==NULL && root->right==NULL)) return true;
- if(isValidBST(root->left)) {
- TreeNode *p=root->left;
- while(p!=NULL && p->right!=NULL) {
- p=p->right;
- }
- if(p==NULL || p->val<root->val) lflag=true;
- }
- if(isValidBST(root->right)) {
- TreeNode *p=root->right;
- while(p!=NULL && p->left!=NULL) {
- p=p->left;
- }
- if(p==NULL || p->val>root->val) rflag=true;
- }
- if(lflag&&rflag) return true;
- return false;
- }