LintCode 97 验证二叉查找树

来源:互联网 发布:怎么找放单的淘宝商家 编辑:程序博客网 时间:2024/05/29 18:05

题目

http://www.lintcode.com/zh-cn/problem/validate-binary-search-tree/

给定一个二叉树,判断它是否是合法的二叉查找树(BST)

一棵BST定义为:

  • 节点的左子树中的值要严格小于该节点的值。
  • 节点的右子树中的值要严格大于该节点的值。
  • 左右子树也必须是二叉查找树。
  • 一个节点的树也是二叉查找树。
样例

一个例子:

  2 / \1   4   / \  3   5

上述这棵二叉树序列化为 {2,1,4,#,#,3,5}.

方法:利用中序遍历是否递增来判断

C++代码

class Solution{public:void inorder(TreeNode *root ,vector<int> &res){if(root == NULL)  return;inorder(root->left,res);res.push_back(root->val);inorder(root->right,res);}bool isValidBST(TreeNode*root){    vector<int> res;    if(!root)              return true;inorder(root,res);for(int i = 0;i <res.size()-1;i++){if(res[i] >= res[i+1])return false;}   return true;}};

Python代码

def isValidBST(self, root):        # write your code here        if not root:            return True        return self._isValidBST(root.left,root.val,None)and \        self._isValidBST(root.right,None,root.val)           def _isValidBST(self,root,lmax,rmin):        if not root:            return True        if lmax and (root.val >=lmax):            return False        if rmin and (root.val <= rmin):            return False        return self._isValidBST(root.left,root.val,rmin)and\               self._isValidBST(root.right,lmax,root.val)