98、验证二叉搜索树
class Solution {
TreeNode pre=null;
int max=0;
public boolean isValidBST(TreeNode root) {
infixOrder(root);
if(max!=0) return false;
return true;
}
public void infixOrder(TreeNode root){
if(root==null) return ;
infixOrder(root.left);
if(pre!=null&&pre.val>=root.val) {
max++;
}
pre=root;
infixOrder(root.right);
}
}
450、删除二叉搜索树中的节点
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root==null) return root;
//在递归的时候要考虑方法的返回值,因为返回值是TreeNode,所以使用递归时要赋值给返回值类型的变量
if(root.val>key){
//去左子树删除结点,左子树删除完结点后,成为新的根结点的左子树
root.left=deleteNode(root.left,key);
}else if(root.val<key){
//去右子树删除结点,右子树删除完结点后,成为新的根结点的右子树
root.right=deleteNode(root.right,key);
}else{ //删除的就是本结点
if(root.left==null) {
return root.right;
}else if(root.right==null) {
return root.left;
}else if(root.left!=null&&root.right!=null){
TreeNode node=root.right;
while(node.left!=null){
node=node.left;//寻找欲删除节点右子树的最左节点
}
node.left=root.left; //将欲删除节点的左子树成为其右子树的最左节点的左子树
return root.right; //把根结点删除,根结点的左子树变成了根结点的右子树的左节点,那么就只剩下根结点的右子树了
}
}
return root;
}
}
701、二叉搜索树中的插入操作
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root==null) return new TreeNode(val);
if(root.val>val){
root.left=insertIntoBST(root.left,val);
}else if(root.val<val){
root.right=insertIntoBST(root.right,val);
}
return root;
}
}