只要这个结点第一次出现在p和q之间 就是最近公共祖先。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null) return null;
while(root!=null){
if(p.val<root.val&&q.val<root.val){
root=root.left;
}else if(p.val>root.val&&q.val>root.val){
root=root.right;
}else return root;
}
return root;
}
}
第二题,(迭代法
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root==null){
return new TreeNode(val);
}
TreeNode cur=root;
TreeNode pre=null;
while(cur!=null){
pre=cur;//更新pre
if(val<cur.val){
cur=cur.left;
}else if(val>cur.val){
cur=cur.right;
}else{
return root;
}
}
if(val<pre.val){
pre.left=new TreeNode(val);
}else if(val>pre.val){
pre.right=new TreeNode(val);
}
return root;
}
}