链接力扣235. 二叉搜索树的最近公共祖先
思路
// 二叉搜索树的最近公共祖先,可以根据值判断
class Solution {public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {// 如果p、q在左子树if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);// 如果p、q在右子树if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);return root;}
}
链接力扣701.二叉搜索树中的插入操作
思路
class Solution {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{root.right = insertIntoBST(root.right,val);}return root;}
}
链接力扣450.删除二叉搜索树中的节点
思路
class Solution {public TreeNode deleteNode(TreeNode root, int key) {// 涉及二叉搜索树,中序较好if(root == null) return null;if(root.val > key) root.left = deleteNode(root.left,key);if(root.val < key) root.right = deleteNode(root.right,key);// 有相等的值,需要删除,分情况if(root.val == key){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;root = root.right;return root;}}return root;}
}