leetcode每日一题(2020.09.27) 235. 二叉搜索树的最近公共祖先

题目

235. 二叉搜索树的最近公共祖先
236. 二叉树的最近公共祖先

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

安安题解 2020.09.27

安安思路

先找到两个节点的路径
然后判断这两条路径种最后一个相同的值

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */


class Solution {
    //res存放的是从根节点到要求的两个节点的路径
    List<List<TreeNode>> list = new ArrayList<>();
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode res = null;

        if(root == null){
            return res;
        }

        dfs(root, p, new ArrayList<TreeNode>());
        dfs(root, q, new ArrayList<TreeNode>());
        //System.out.println(list);

        List<TreeNode> path1 = list.get(0);  //第一个节点的路径
        List<TreeNode> path2 = list.get(1);  //第二个节点的路径
        
        return func(path1, path2);
    }

    //从两个数组里面,从后向前找第一个相等的数
    public TreeNode func(List<TreeNode> path1, List<TreeNode> path2){
        for(int i = path1.size()-1; i >= 0; i--){
            for(int j = path2.size()-1; j >= 0; j--){
                //System.out.println(path1.get(i).val + " " + path2.get(j).val);
                if(path1.get(i) == path2.get(j)){
                    return path1.get(i);
                }
            }
        }
        return null;
    }

    //dfs找到两个节点的路径
    public void dfs(TreeNode root, TreeNode p, List<TreeNode> path){
        path.add(root);

        if(root == p){
            list.add(new ArrayList<TreeNode>(path));
            path.remove(path.size()-1);
            return;
        }

        if(root.left != null){
            dfs(root.left, p, path);
        }
        if(root.right != null){
            dfs(root.right, p, path);
        }

        path.remove(path.size()-1);
    }
}

改进:利用二叉搜索树的特点 leetcode官解

我的题解可以是 236. 二叉树的最近公共祖先 通用的题解(已验证,236可以通过)
对于该题,可以利用二叉搜索树的特点

提炼知识点:如何在两个数组中找最后一个相同的值?

本题中数组是无序的,只能用for循环去做
如果数组是有序的话,就可以用双指针去做了

//2020.09.27(日)
 //从两个数组里面,从后向前找第一个相等的数
    public TreeNode func(List<TreeNode> path1, List<TreeNode> path2){
        for(int i = path1.size()-1; i >= 0; i--){
            for(int j = path2.size()-1; j >= 0; j--){
                //System.out.println(path1.get(i).val + " " + path2.get(j).val);
                if(path1.get(i) == path2.get(j)){
                    return path1.get(i);
                }
            }
        }
        return null;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安安csdn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值