[LeetCode]Validate Binary Search Tree, 解题报告
来源:互联网 发布:阿里云学生9.9 编辑:程序博客网 时间:2024/05/22 06:55
题目
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.
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.
思路
可能大家第一时间都会想到用递归处理,但是一定要注意的是这道题目不是单独的递归判断一个根节点和两个孩子就能解决问题的,如图所示:
如果这是单独判断每颗子树,都满足BST的要求,但是整体来看就不行了,因为根节点的左子树中有大于根节点的节点存在,右子树中有小于根节点的节点存在
因此,可以考虑上下界的方式,然后判断每颗根节点即可
AC代码
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public static boolean isValidBST(TreeNode root) { return isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } public static boolean isValidBST(TreeNode root, int min, int max) { if (root == null) { return true; } if (root.val <= min || root.val >= max) { return false; } return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max); }}
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
- 如何实现窗口阴影效果 (SysShadow、分层窗口、DWM)
- 我很优秀,但是我需要做到是让所有人看到
- 关于闭包(二)
- android xml 编写图片
- GOLDEN PENNY STOCK MILLIONAIRES
- [LeetCode]Validate Binary Search Tree, 解题报告
- PHP再学习5——RESTFul框架 远程控制LED
- java 布局之FlowLayout
- C#发现之旅:于动态编译的VB.NET脚本引擎
- Flatten Binary Tree to Linked List
- Could not find the required version of the Java(TM)2 Runtime Environment in '(null)' 解决办法
- 最大公约数--欧几里得算法
- hdoj2011解题报告
- 查看sql语句的执行时间