235. 二叉搜索树的最近公共祖先
public class Solution {
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root.val == p.val || root.val == q.val || root == null) return root;
if(root.val > p.val && root.val > q.val) return LowestCommonAncestor(root.left,p,q);
else if(root.val < p.val && root.val < q.val) return LowestCommonAncestor(root.right,p,q);
else return root;
}
}
701. 二叉搜索树中的插入操作
如下为自己原先思路代码,思路错误。
public class Solution {
public TreeNode InsertIntoBST(TreeNode root, int val) {
if(root.left == null && root.right == null) return root;
TreeNode leaf;
if(root.val > val)
{
leaf = InsertIntoBST(root.left, val);
}
else
{
leaf = InsertIntoBST(root.right, val);
}
if(val > leaf.val)
{
leaf.right = new TreeNode(val);
}
else
{
leaf.left = new TreeNode(val);
}
return root;
}
}