zoukankan      html  css  js  c++  java
  • 98. Validate Binary Search Tree

    98. 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.
    
    Example 1:
    
        2
       / 
      1   3
    
    Binary tree [2,1,3], return true.
    
    Example 2:
    
        1
       / 
      2   3
    
    Binary tree [1,2,3], return false. 
    

    解析

    • 需要注意的是,左子树的所有节点都要比根节点小,而非只是其左孩子比其小,右子树同样。这是很容易出错的一点是,很多人往往只考虑了每个根节点比其左孩子大比其右孩子小。如下面非二分查找树,如果只比较节点和其左右孩子的关系大小,它是满足的。
    • 从根节点开始递归,遍历所有的节点。并且在每个节点处,分别遍历其左右子树,判断其左子树的最大值比其小,右子树的最小值比其大。时间复杂度为O(n^2)。参考:【LeetCode】Validate Binary Search Tree 解题报告
    • 这题实际上简化了难度,因为一般的二叉搜索树是左<=根<右,而这道题设定为左<根<右,那么就可以用中序遍历来做。因为如果不去掉左=根这个条件的话,那么下边两个数用中序遍历无法区分:
      20 20
      /
      20 20
    • 它们的中序遍历结果都一样,但是左边的是BST,右边的不是BST。去掉等号的条件则相当于去掉了这种限制条件。参考:98. Validate Binary Search Tree
    class Solution_98 {
    public:
    
    	//bug
    	bool isValidBST_bug(TreeNode* root) {
    
    		if (!root||(!root->right&&!root->left))
    		{
    			return true;
    		}
    		
    		if (root->left!=NULL&&root->left->val>=root->val)
    		{
    			return false;
    		}
    		if (root->right!=NULL&&root->right->val<=root->val)
    		{
    			return false;
    		}
    		return isValidBST_bug(root->left) && isValidBST_bug(root->right);
    	}
    
    	// 二分查找树的中序遍历结果是一个递增序列
    	TreeNode* pre = NULL;
    	void InOrder(TreeNode* root,int &res)
    	{
    		if (!root)
    		{
    			return;
    		}
    		InOrder(root->left, res);
    		if (!pre)
    		{
    			pre = root;
    		}
    		else
    		{
    			if (root->val<=pre->val)
    			{
    				res = 0;
    			}
    			pre = root;
    		}
    
    		InOrder(root->right,res);
    		return;
    	}
    	bool isValidBST(TreeNode *root) {
    
    		if (!root)
    		{
    			return true;
    		}
    		int res = 1;
    		InOrder(root,res);
    
    		if (res==0)
    		{
    			return false;
    		}
    		return true;
    	}
    };
    

    题目来源

  • 相关阅读:
    WCF开发框架形成之旅---WCF的几种寄宿方式
    使用Winform程序作为WCF服务的宿主
    Winfrom 使用WCF 实现双工通讯
    WCF简单实例--用Winform启动和引用
    ASP.NET用QQ,网易发送邮件以及添加附件
    神经网络浅讲:从神经元到深度学习
    jQuery EasyUI combobox多选及赋值
    easyui combobox 带 checkbox 亲自验证
    天地图api地址
    1-3Controller之Response
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8831998.html
Copyright © 2011-2022 走看看