Leetcode 98. Validate Binary Search Tree

来源:互联网 发布:万网二手域名交易平台 编辑:程序博客网 时间:2024/06/16 01:30

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
原创粉丝点击