【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
- [LeetCode]Validate Binary Search Tree, 解题报告
- 【LeetCode】Validate Binary Search Tree 解题报告
- [LeetCode] Validate Binary Search Tree 解题报告
- 【LeetCode】Validate Binary Search Tree 解题报告
- LeetCode(98) Validate Binary Search Tree解题报告
- [leetcode] 98. Validate Binary Search Tree 解题报告
- [Leetcode] 98. Validate Binary Search Tree 解题报告
- [leetcode]98. Validate Binary Search Tree@Java解题报告
- [LeetCode]Binary Search Tree Iterator,解题报告
- 【LeetCode】Recover Binary Search Tree 解题报告
- LeetCode-Binary Search Tree Iterator-解题报告
- [LeetCode] Recover Binary Search Tree 解题报告
- Leetcode 98. Validate Binary Search Tree 验证二叉搜索树 解题报告
- LeetCode: Validate Binary Search Tree
- [Leetcode] Validate Binary Search Tree
- LeetCode : Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- [LeetCode] Validate binary search tree
- SharePoint 2013 ECB 自定义扩展菜单
- ACM 兄弟郊游问题
- Intellij IDEA问题:Error during artifact deployment. See server log for details
- Python正则表达式学习(5)——re.findall()
- C#学习之关于lock
- 【LeetCode】Validate Binary Search Tree 解题报告
- 告诉学生:这才是中、高考阅卷真正的“潜规则”!
- Eclipse建立Maven maven-archtype-webapp项目
- Angular4学习笔记(三):router
- HDU2214 函数图像
- Hive2.1.1、Hadoop2.7.3 部署
- 类与对象
- 双核处理问题(2017网易春招)
- 5.循环