二叉搜索树的判断 leetcode原题
来源:互联网 发布:华为软件培训 编辑:程序博客网 时间:2024/06/08 16:45
二叉查找树(Binary Search Tree)
(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树(这也是判断二叉搜索树的标准,即条件):
(1) 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)它的左、右子树也分别为二叉排序树。
leetcode题目:
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.
以下程序是判断一棵树
判断过程:
(1)从根节点开始判断:左右两个节点的大小是否符合:左节点值<根节点值<右节点值,并依次遍历判断整棵树左子树所有节点和右子树所有节点是否满足二叉搜索树性质(1)和(2);
(2)根节点检测完成后,开始左右子树的遍历,判断它们是不是二叉搜索树
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public
class
Solution {
public
static
boolean
IsSubtreeLessThan(TreeNode t,
int
val) {
if
(t ==
null
)
return
true
;
return
(t.val < val && IsSubtreeLessThan(t.left, val) && IsSubtreeLessThan(t.right, val));
}
public
static
boolean
IsSubtreeMoreThan(TreeNode t,
int
val) {
if
(t==
null
)
return
true
;
return
(t.val>val && IsSubtreeMoreThan(t.left, val) && IsSubtreeMoreThan(t.right, val));
}
public
boolean
isValidBST(TreeNode root) {
if
(root ==
null
)
return
true
;
return
(IsSubtreeLessThan(root.left, root.val) && IsSubtreeMoreThan(root.right, root.val)
&& isValidBST(root.left) && isValidBST(root.right));//对应上述“”判断过程“”
}
}
- 添加笔记
阅读全文
0 0
- 二叉搜索树的判断 leetcode原题
- LeetCode—判断是否为二叉搜索树
- 每天一道LeetCode-----判断某棵树是否是二叉搜索树
- 二叉搜索树的后序判断
- 判断二叉搜索树的合法性
- 判断是否相同的二叉搜索树
- 二叉树系列四:Leetcode#98判断二叉树是否为二叉搜索树(BST)
- LeetCode(Validate Binary Search Tree) 判断一个二叉树是否是二叉搜索树
- 判断给定二叉树是否是二叉搜索树(LeetCode: Validate Binary Search Tree)
- Leetcode:Validate Binary Tree 判断一个二叉树是否为二叉搜索树
- 二叉树搜索树--leetcode
- 二叉搜索树的后序遍历序列序列判断是否是二叉搜索树
- leetcode 669二叉搜索树
- 二叉搜索树(篇1)判断数组是不是二叉搜索树后序遍历的结果
- 判断二叉搜索树的后续遍历序列
- 判断二叉搜索树的前序遍历序列
- Validate Binary Search Tree 二叉搜索树的合法判断
- 判断是否是二叉搜索树的后序遍历
- DPDK之(九)——收发包分析
- JVM性能优化, Part 2 ―― 编译器
- Systick分析
- windows关闭windows正在检查该问题的解决方案
- hibernate 学习细节
- 二叉搜索树的判断 leetcode原题
- 世界级机器学习专家都有谁?有关 AI 你不能不知道的6个人物
- 使用Timer+servletListener实现web服务的任务调度
- 计算机视觉——SIFT算法之高斯金字塔
- 安卓开发---仿网易云小火箭dialog一个简单的自动更新弹窗以及下载apk
- Intellij IDEA17 关于maven-generator插件,无法在右侧显示的问题
- select和radio常用操作
- <link>标签的属性
- 虚拟机安装的系统界面很大的解决办法