二叉搜索树的操作
2018-07-31 15:46:34
一、插入 Insert into a Binary Search Tree
问题描述:


问题求解:
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
TreeNode node = new TreeNode(val);
return node;
}
if (root.val > val) root.left = insertIntoBST(root.left, val);
else root.right = insertIntoBST(root.right, val);
return root;
}
二、删除 Delete Node in a BST
问题描述:


问题求解:
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 minNode = root.right;
while (minNode.left != null) minNode = minNode.left;
root.val = minNode.val;
root.right = deleteNode(root.right, root.val);
}
return root;
}

浙公网安备 33010602011771号