【题解】【BST】【Leetcode】Validate Binary Search Tree

时间:2021-02-17 08:12:45

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.

思路:

这题其实考查的是BST的定义,下面code的是CC150v5上的第一种答案简化版,同样借鉴中序遍历的思想,但是只保存当前点上家的值,判断当前点是否大于上家。

代码:

 bool isValidBST(TreeNode *root) {
int init = INT_MIN;
return isValidNode(root, init);
}
bool isValidNode(TreeNode *root, int& lastVal){
if(root == NULL)
return true; if(!isValidNode(root->left, lastVal))
return false; if(root->val <= lastVal) //不是<而是<=,failed {1,1}=>false
return false;
lastVal = root->val; if(!isValidNode(root->right, lastVal))
return false; return true;//忘写最后一句了
}