力扣算法学习day16-3
235-二叉搜索树的最近公共祖先
题目


代码实现
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(p.val < root.val && q.val < root.val){
return lowestCommonAncestor(root.left,p,q);
} else if(p.val > root.val && q.val > root.val){
return lowestCommonAncestor(root.right,p,q);
} else{
return root;
}
}
}
701-二叉搜索树中的插入操作
题目



代码实现
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) return new TreeNode(val);
TreeNode head = root;
TreeNode pre = root;
while (root != null) {
pre = root;
if (root.val > val) {
root = root.left;
} else if (root.val < val) {
root = root.right;
}
}
if (pre.val > val) {
pre.left = new TreeNode(val);
} else {
pre.right = new TreeNode(val);
}
return head;
}
}
450-做了大半,错误,明日修改。
|