235. 二叉搜索树的最近公共祖先
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if ((root.val >= p.val && root.val <= q.val) || (root.val <= p.val && root.val >= q.val)) {
return root;
}
if (root.val > p.val) {
return lowestCommonAncestor(root.left, p, q);
}
return lowestCommonAncestor(root.right, p, q);
}
701.二叉搜索树中的插入操作
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
if (val < root.val) {
root.left = insertIntoBST(root.left, val);
} else {
root.right = insertIntoBST(root.right, val);
}
return root;
}
public TreeNode insertIntoBST2(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
TreeNode cur = root, pre = null;
while (cur != null) {
if (cur.val < val) {
pre = cur;
cur = cur.right;
} else {
pre = cur;
cur = cur.left;
}
}
if (pre.val < val) {
pre.right = new TreeNode(val);
} else {
pre.left = new TreeNode(val);
}
return root;
}
450.删除二叉搜索树中的节点
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return null;
}
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;
if(root.right == null) return root.left;
TreeNode right = root.right;
while(right.left != null){
right = right.left;
}
root.val = right.val;
root.right=deleteNode(root.right,right.val);
}
return root;
}
标签:right,TreeNode,val,第三,题写,return,null,root,快又准
From: https://www.cnblogs.com/Chain-Tian/p/17020943.html