题目
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;
}