二叉搜索树中的插入、搜索、删除操作
/**
* 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) return new TreeNode(val);
// insert into the right subtree
if (val > root.val) root.right = insertIntoBST(root.right, val);
// insert into the left subtree
else root.left = insertIntoBST(root.left, val);
return root;
}
}
//搜索
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
while (root != null && val != root.val)
root = val < root.val ? root.left : root.right;
return root;
}
}
//删除操作见第450题
网友评论