这两天在学数据结构,做了几道leetcode上的探索题
https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/7/trees/48/
题目:验证二叉搜索树
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
一个二叉搜索树具有如下特征:
- 节点的左子树只包含小于当前节点的数。
- 节点的右子树只包含大于当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入: 2 / \ 1 3 输出: true
示例 2:
输入: 5 / \ 1 4 / \ 3 6 输出: false 解释: 输入为: [5,1,4,null,null,3,6]。 根节点的值为 5 ,但是其右子节点值为 4 。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
分析:
当前节点只能看到并判断其子节点,所以遍历每个节点进行判断是必须的.所以先写个遍历.
public boolean travel(TreeNode root){
if (root == null){
return true;
}
//对当前节点进行判断,是左侧子树都小于其本身,右侧都大于
if (!isBinaryLeft(root,root.left) || !isBinaryRight(root,root.right)){
return false;
}
//返回遍历结果,只要有节点不满足,则为false
return travel(root.left) && travel(root.right);
}
接下来写对左右两侧的判断,需要所有子节点都满足条件,所以判断中也要对子节点遍历.
public boolean isBinaryLeft (TreeNode root, TreeNode tmp) {
if (tmp == null) {
return true;
}
//判断当前节点
if (tmp.val >= root.val) {
return false;
} else {
//递归判断当前节点的子节点
return isBinaryLeft(root,tmp.left) && isBinaryLeft(root,tmp.right);
}
}
public boolean isBinaryRight (TreeNode root, TreeNode tmp) {
if (tmp == null) {
return true;
}
//判断当前节点
if (tmp.val <= root.val) {
return false;
} else {
//递归判断当前节点的子节点
return isBinaryRight(root,tmp.left) && isBinaryRight(root,tmp.right);
}
}
总结:
二叉树的结构更适用于递归,之前试着用迭代来写遍历,感觉很麻烦,逻辑也不太好理顺