【LeetCode】Validate Binary Search Tree 解题报告

来源:互联网 发布:网络道德的原则有 编辑:程序博客网 时间:2024/06/05 15:27

【LeetCode】Validate Binary Search Tree 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/validate-binary-search-tree/#/description

题目描述:

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:

    2   / \  1   3Binary tree [2,1,3], return true.    1   / \  2   3  Binary tree [1,2,3], return false.

Ways

判断一棵树是不是BST,那么按照定义,左子树的值要在(min,mid)之间,右子树的值在(mid,max)之间,这个mid值并不是中位数而是当前节点的值。这么一想,就可以很快的判断是不是符合BST的定义了。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isValidBST(TreeNode root) {        return isValid(root, Long.MIN_VALUE, Long.MAX_VALUE);    }    public boolean isValid(TreeNode root, long min, long max){        if(root == null){            return true;        }        long mid = root.val;        if(mid <= min || mid >= max){            return false;        }        return isValid(root.left, min, mid) && isValid(root.right, mid, max);    }}

Date

2017 年 4 月 17 日

0 0
原创粉丝点击