描述
给定一棵二叉树以及这棵树上的两个节点 o1 和 o2,请找到 o1 和 o2 的最近公共祖先节点。
示例1
分析:
最近公共祖先和o1,o2有三种关系:
- o1,o2分别在祖先左右两侧
- 祖先是o1,o2在祖先左/右侧
- 祖先是o2,o1在祖先左/右侧
使用dfs深度遍历,如果节点为o1,o2中其中一个直接返回,如果节点超过叶子节点也返回
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
function lowestCommonAncestor( root , o1 , o2 ) {
// 先序遍历二叉树,遇到o1入栈s1,遇到o2入栈s2;再依次出栈,寻找最近的公共祖先
return CommonAncestor(root, o1, o2).val;
}
function CommonAncestor(root, o1, o2){
//1. 遍历到了叶子节点、o1 或 o2 为祖先节点
if(root == null || root.val == o1 || root.val == o2){
return root;
}
let left = CommonAncestor(root.left, o1, o2); //左侧
let right = CommonAncestor(root.right, o1, o2); //右侧
if(left == null){ //o1、o2都在右侧
return right;
}
if(right == null){ //o1、o2 都在左侧
return left;
}
return root; //在左右两侧
}
module.exports = {
lowestCommonAncestor : lowestCommonAncestor
};