1. 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先
题目解析:
题目:
236. 二叉树的最近公共祖先 - 力扣(LeetCode)
最近公共祖先的意思就是,找到他们俩个指定结点的相交结点
我们分为这四种情况:
1. root就是q/p的其中一个,那么root就是最近公共祖先
2. 如果p和q分布在root俩侧 那么root就是最近公共祖先
3. 如果p和q在同一侧, root先碰到谁,谁就是最近公共祖先
4. 在3的基础上如果p,q在同一层,那么root就是最近公共祖先
具体我举了个例子来看递归的情况,有需要的可以看看
此时这里后面有一部分代码是可以这么合并
我们还有另外一种写法,也就是之前求链表的时候,链表分叉了我们找到分叉的交点.
我们使用俩个栈来保存经过p,q的路径上的结点,然后我们计算俩个栈的大小,让大的那个栈先出多余的元素,当俩个栈的大小一致的时候,我们就同时出栈,直到出来的俩个元素相等为止.(该方法多练,不太熟)
1> 获取p,q的路径栈
2> 出栈多的元素
3> 同时出栈元素,直到出栈的元素一样
具体代码:
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){
//如果root是空,那么就没有公共结点,返回Null
if(root == null) {
return null;
}
//如果root就是p,q中的一个,返回root
if(p == root || q == root) {
return root;
}
//获取左右子树
TreeNode leftTree = lowestCommonAncestor(root.left,p,q);
TreeNode rightTree = lowestCommonAncestor(root.right,p,q);
//如果左右子树都不为空,说明p,q分别分布在左右子树上
if(leftTree != null && rightTree != null) {
return root;
}
//左子树为空,那么都在右子树上
if(leftTree == null && rightTree != null) {
return rightTree;
}
//右子树为空,那么都在左子树上
if(leftTree != null && rightTree == null){
return leftTree;
}
return null;
}
法2的具体代码:
public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {