235. 二叉搜索树的最近公共祖先 Lowest Common Ancestor of a Binary Search Tree - LeetCode
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (p.val < root.val && q.val < root.val) return lowestCommonAncestor(root.left, p, q);
if (p.val > root.val && q.val > root.val) return lowestCommonAncestor(root.right, p, q);
return root;
}
}
701.二叉搜索树中的插入操作 Insert into a Binary Search Tree - LeetCode
/**
* 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) {
TreeNode newNode = new TreeNode(val);
return newNode;
}
if (val < root.val) {
root.left = insertIntoBST(root.left, val);
} else if (val > root.val) {
root.right = insertIntoBST(root.right, val);
}
return root;
}
}
450.删除二叉搜索树中的节点 Delete Node in a BST - LeetCode
TreeNode delete(root, key)
if (root == null) return null;
if (root.val == key)
if (root.left == null && root.right == null) return null;
else if (root.left != null && root.right == null) return root.left;
else if (root.left == null && root.right != null) return root.right;
else
cur = cur.right;
while(cur.left != null) cur = cur .left;
cur.left = root.left;
好麻烦,感觉还是没弄懂
/**
* 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 deleteNode(TreeNode root, int key) {
root = delete(root,key);
return root;
}
private TreeNode delete(TreeNode root, int key) {
if (root == null) return null;
if (root.val > key) {
root.left = delete(root.left, key);
} else if (root.val < key) {
root.right = delete(root.right, key);
} else {
if (root.left == null) return root.right;
if (root.right == null) return root.left;
TreeNode cur = root.right;
while (cur.left != null) {
cur = cur.left;
}
root.val = cur.val;
root.right = delete(root.right, cur.val);
}
return root;
}
}