Leetcode 98. Validate Binary Search Tree

https://leetcode.com/problems/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


Implement a function to check if a binary tree is a binary search tree.
验证一个2叉树是否是2叉查找树;

有效2叉树的定义:left<=current<right

思路1:中序遍历BT,然后检查数组是否已排序;
问题:这种思路仅在BT中无重复元素情况下有效;
另: 取决于题目对于BST的定义。  是否考虑相等的情况。思路1 先天无法解决重复元素的测试用例。因此无法通过leetcode

static List<int> eleList;
    public bool IsValidBST(TreeNode root)
        {
             eleList = new List<int>();
            if (root != null)
            {
                IsValidBST(root.left);
                eleList.Add(root.val);
                IsValidBST(root.right);
            }
            return checkListOrdered(eleList);
        }

        private  bool checkListOrdered(List<int> list)
        {
            if (list == null || list.Count == 0||list.Count==1) return true;
            int i = 0,j = 1;
            while (i < list.Count && j < list.Count)
            {
                if (list[j] < list[i])
                    return false;
                i++;
                j++;
            }
            return true;
        }






思路2 :Min/Max解决方案(使用这种)
利用BST的定义,如下:
BST特点:
1 若左子树不空,左子树所有节点值小于等于根节点值
2 若右子树不空,右子树所有节点值大于等于根节点值
3 左右字数也是2叉查找树
  

1 令Min=Integer.Min;  Max=Integer.Max; root一定符合
2 左子树中,Min=Integer.Min; Max=root
3 右子树中,Min=root, Max=Integer.Max;
4 递归左子树时,最大值在更新; 递归右子树时,最小值在更新;
5 有任何不符合check的,直接返回false

注意事项:
注意事项: 本思路中,根据BST的定义,左节点<root<右节点;所以:如果小于等于和大于等于->false。
时间复杂度:O(N)
注意事项:递归算法中,一定要妥善处理base cases和 null cases;

 public bool IsValidBST(TreeNode root)
        {
            return IsValidBST(root,Int64.MinValue, Int64.MaxValue);
        }

        public bool IsValidBST(TreeNode root, Int64 min, Int64 max)
        {
            //base case,返回true
            if (root == null)
                return true;
            //root.data<=min||root.data>=max =>false
            if (root.val <= min || root.val >= max)
                return false;

            //检查左子树和右子树,有任意一个不符合=>返回false
            if (!IsValidBST(root.left, min, root.val) || !IsValidBST(root.right, root.val, max))
                return false;

            return true;
        }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值