个人记录-LeetCode 98. Validate Binary Search Tree
来源:互联网 发布:fetch.js官网 编辑:程序博客网 时间:2024/06/06 02:52
问题:
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
1、The left subtree of a node contains only nodes with keys less than the node’s key.
2、The right subtree of a node contains only nodes with keys greater than the node’s key.
3、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
这个问题就是判断给定的树是否为二分查找树。
二分查找树的特点上文已经写的很清楚了:
要求根节点左子树节点的值全部小于根节点的值;
同时要求根节点右子树节点的值全部大于根节点的值。
代码示例:
对于这个问题,递归足以满足它的要求,
对应代码类似于:
/** * 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 isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE); } private boolean isValidBST(TreeNode root, long minValue, long maxValue) { //当前根节点为null时,返回true if (root == null) { return true; } //当前节点的值必须在minValue和maxValue之间 if (root.val <= minValue || root.val >= maxValue) { return false; } //对于左子树,其最大值要小于root.val //对于右子树,其最小值要大于root.val return isValidBST(root.left, minValue, root.val) && isValidBST(root.right, root.val, maxValue); }}
0 0
- 个人记录-LeetCode 98. 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
- [leetcode] 98.Validate Binary Search Tree
- [leetcode] 98.Validate Binary Search Tree
- [Leetcode] 98. Validate Binary Search Tree @python
- Leetcode 98. Validate Binary Search Tree
- [LeetCode]98. Validate Binary Search Tree
- leetcode 98. Validate Binary Search Tree
- *LeetCode 98. Validate Binary Search Tree
- 98. Validate Binary Search Tree LeetCode
- LeetCode 98. Validate Binary Search Tree
- LeetCode 98. Validate Binary Search Tree
- LeetCode *** 98. Validate Binary Search Tree
- 98. Validate Binary Search Tree-leetcode-java
- [leetcode] 98. Validate Binary Search Tree
- 连接本地Oracle 11g时 ORA-12514:TNS:监听程序当前无法识别连接描述符中请求的服务
- 保存1
- 自定义UICollectionViewFlowLayout实现section悬浮
- UE添加鼠标右键打开
- linux sed 批量替换字符串
- 个人记录-LeetCode 98. Validate Binary Search Tree
- Perm--全排列函数
- HDU2031进制转换
- WdatePicker
- maven内存溢出处理方法
- Linux NFS服务器的安装与配置
- git 创建一个新branch,push到远端后,通过网页可以看到新建的branch
- AndroidStudio 对于library工程生成的jar包路径
- emboss 安装使用