二叉树的最近公共祖先 LeetCode 236
题目链接:[LeetCode 236 - 中等]
思路
情况一:p和q分别位于左右子树中 情况二:p或者q为节点本身,另外一个位于其子树中
本题终止条件: if (root == q || root == p || root == NULL) return root;
递归逻辑:
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left==null && right==null){
return null;
}else if(left==null && right!=null){
return right;
}else if(left!=null && right==null){
return left;
}else{
return root;
}
递归:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q){
return root;
}
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left==null && right==null){
return null;
}else if(left==null && right!=null){
return right;
}else if(left!=null && right==null){
return left;
}else{
return root;
}
}
}
二叉搜索树的最近公共祖先 LeetCode 235
题目链接:[LeetCode 235 - 中等]
思路
同上+二叉搜索树的特性
递归(不使用二叉搜索树的特性):
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null || root==p || root==q){
return root;
}
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left==null && right==null){
return null;
}else if(left==null && right!=null){
return right;
}else if(left!=null && right==null){
return left;
}else{
return root;
}
}
}
递归(使用二叉搜索树的特性):
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return root;
long a = root.val - p.val;
long b = root.val - q.val;
if(a * b <= 0){
return root;
}else if(root.val > p.val){
return lowestCommonAncestor(root.left,p,q);
}else{
return lowestCommonAncestor(root.right,p,q);
}
}
}
二叉搜索树中的插入操作 LeetCode 701
题目链接:[LeetCode 701 - 简单]
思路
利用二叉搜索树的特性 -> 判断新的节点应该插入什么位置 使用递归的方式,先确定终止条件:三个 -> 该节点为空,直接插入 -> 该节点的左子树为空且新节点的值小于根节点 -> 该节点的右子树为空且新节点的值大于根节点
递归:
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
TreeNode node = new TreeNode(val);
if(root == null) return node;
if(root.val > node.val && root.left == null){
root.left = node;
return root;
}else if(root.val < node.val && root.right == null){
root.right = node;
return root;
}
TreeNode left = new TreeNode();
TreeNode right = new TreeNode();
if(root.val > node.val){
left = insertIntoBST(root.left,val);
}else{
right = insertIntoBST(root.right,val);
}
return root;
}
}