【英雄算法六月集训】Day19
700. 二叉搜索树中的搜索
二叉搜索树的特征就是,左侧所有值都小于根节点 右侧的值大于根节点,有点二分搜索的味道
特征:
二叉搜索树BST
先序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if(root == null){
return null;
}
if(val == root.val){
return root;
}
if(val < root.val){
return searchBST(root.left,val);
}else{
return searchBST(root.right,val);
}
}
}
剑指 Offer 54. 二叉搜索树的第k大节点
通过中序遍历将树转成数组,然后直接下标访问数据
特征:
二叉搜索树BST
中序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int[] kval=new int[100000];
int n=0;
public void inorder(TreeNode root){
if(root!=null){
inorder(root.left);
kval[n++]=root.val;
inorder(root.right);
}
}
public int kthLargest(TreeNode root, int k) {
inorder(root);
return kval[n-k];
}
}
701. 二叉搜索树中的插入操作
特征:
二叉搜索树BST
中序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root==null){
return new TreeNode(val);
}
if(val<root.val){
root.left= insertIntoBST(root.left,val);
}
if(val>root.val){
root.right= insertIntoBST(root.right,val);
}
return root;
}
}
面试题 04.05. 合法二叉搜索树
中序遍历访问每个节点,然后用pre记录下这个节点的值,用于下个节点遍历时的比较,如果下一个节点的值,比这个值大,则不合法
特征:
二叉搜索树BST
中序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int INIIT = 32423432;
int pre;
boolean flag;
public void inorder(TreeNode root){
if(root!=null){
inorder(root.left);
if(pre !=INIIT&&root.val <= pre){
flag= false;
}
pre = root.val;
inorder(root.right);
}
}
public boolean isValidBST(TreeNode root) {
pre = INIIT;
flag=true;
inorder(root);
return flag;
}
}