LeetCode-98. Validate Binary Search Tree
来源:互联网 发布:veleq电气仿真软件 编辑:程序博客网 时间:2024/06/05 01:19
题目描述
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.
解题思路
判定一棵树是不是二叉查找树,个人感觉应该自下而上的判断,因为判断root节点是否满足条件时,不只是满足root.left.val小于root.val,和root.right.val大于root.val关系,而是还要比较左子树的最大值要小于root.val,同时右子树的最小值要大于root.val。本人自定义了数据类,自下而上的返回各个子树中的最大值和最小值。
代码
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; public boolean isValidBST(TreeNode root) { if(root == null) return true; return validCore(root).flag; } public Result validCore(TreeNode root){ Result left = null; if(root.left == null){ left = new Result(); left.min = root.val; left.max = root.val; }else{ left = validCore(root.left); if(!left.flag || left.max >= root.val){ left.flag = false; return left; } } Result right = null; if(root.right == null){ right = new Result(); right.min = root.val; right.max = root.val; }else{ right = validCore(root.right); if(!right.flag || right.min <= root.val){ right.flag = false; return right; } } right.max = Math.max(right.max,root.val); right.min = Math.min(left.min,root.val); return right; }}class Result{ boolean flag = true; int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE;}
阅读全文
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 @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
- LeetCode - 98. Validate Binary Search Tree
- IO-读写文件
- HTML 显示网页图片 若无法显示图片则显示文字
- 在Myeclipse或者eclipse下创建tld文件步骤详解:
- POI导入Excel表格数据到数据库中
- Angular Material GridList组件
- LeetCode-98. Validate Binary Search Tree
- 以太坊核心概念开发如何用数字货币引领区块链
- opencv编译安装contrib包的注意事项和错误解决
- 数据库探索之旅——初识数据库
- SpringBoot使用自定义的properties
- 浅谈 堆
- javascript方法中new方式和字面量方式的区别
- Linux常用文本处理工具总结备忘(grep,awk,sed,cut...)
- java函数参数中:用参数值带回结果(类似传址)的方式及各种观点辨析