public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null) return null; //左右就够了,因为二叉搜索树就有序了 //递归法 //左 if(root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p,q); //右 if(root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q); return root;
//迭代法
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while (true){ if(root.val > p.val && root.val > q.val){ root = root.left; }else if(root.val < p.val && root.val < q.val){ root = root.right; }else { break; } } return root; }
public class InsertintoaBinarySearchTree { //递归法 public TreeNode insertIntoBST(TreeNode root, int val) { // 如果当前节点为空,也就意味着val找到了合适的位置,此时创建节点直接返回。 if(root == null) { TreeNode node = new TreeNode(val); return node; } if( val < root.val){ root.left = insertIntoBST(root.left, val);// 递归创建右子树 }else if(val > root.val){ root.right = insertIntoBST(root.right, val);// 递归创建左子树 } return root; } }
public class DeleteNodeinaBST { public TreeNode deleteNode(TreeNode root, int key) { //终止条件 if(root == null) return null;//没有找到删的节点 //找到删除节点1。叶子节点(左为空,右为空) if(root.val == key) { if(root.left == null && root.right == null){//2。左右都是空 return null; }else if(root.left == null){//3。左空右不为空 return root.right; }else if(root.right == null){//4。左不为空右为空 return root.left; }else {//5.左右不为空 TreeNode cur = root.right; while (cur.left != null){ cur = cur.left; } cur.left = root.left;//左孩子接到root的left //移除节点 root = root.right; return root; } } if(key < root.val) root.left = deleteNode(root.left,key);//删除节点< root.val if(key > root.val) root.right = deleteNode(root.right, key); return root; } }