二叉搜索树公共祖先
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root.val > p.val && root.val > q.val) {
return lowestCommonAncestor(root.left, p, q);
} else if (root.val < p.val && root.val < q.val) {
return lowestCommonAncestor(root.right, p, q);
}
return root;
}
二叉搜索树中的插入操作
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;
}
删除二叉搜索树中的节点
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) {
return root;
}
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 {
TreeNode cur = root.right;
while(cur.left != null) {
cur = cur.left;
}
cur.left = root.left;
return root.right;
}
}
return root;
}
网友评论