【LeetCode】Validate Binary Search Tree ——合法二叉树

时间:2023-03-09 04:51:12
【LeetCode】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.

【解析】

题意:判断一个二叉树是否为二分查找树。

何为二分查找树?1) 左子树的值都比根节点小;2) 右子树的值都比根节点大;3) 左右子树也必须满足上面两个条件。

需要注意的是,左子树的所有节点都要比根节点小,而非只是其左孩子比其小,右子树同样。这是很容易出错的一点是,很多人往往只考虑了每个根节点比其左孩子大比其右孩子小。如下面非二分查找树,如果只比较节点和其左右孩子的关系大小,它是满足的。

5
  /     \
4      10
      /      \
    3        11

【错误代码示范】【NA】

 /**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
if (root == null) return true;
if (root.left != null && root.val <= root.left.val) return false;
if (root.right != null && root.val >= root.right.val) return false;
return isValidBST(root.left) && isValidBST(root.right);
}
}

正确解法:中序遍历

二分查找树的中序遍历结果是一个递增序列。

 /**
* 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 isValidBST(TreeNode *root) {
if(root==NULL) return true;
bool res = true;
res&=isValidBST(root->left);
if(pre!=NULL&&pre->val>=root->val) res=false;
pre=root;
res&=isValidBST(root->right);
return res;
}
TreeNode *pre=NULL;
};