Problem: 236. 二叉树的最近公共祖先
题目描述
思路
1.先序处理:如果当前节点的值等于任一目标值,那么返回当前节点。(因为题目说了p和q一定存在于二叉树中(这点很重要),所以即便我们遇到q就直接返回,根本没遍历到p,也依然可以断定p在q底下)
2.递归左右子树:对左子树和右子树进行递归调用,查找是否包含目标节点。
3.后序判断:若当前左右子树返回均不为空,则说明当前节点就是最近共同祖先;
复杂度
时间复杂度:
O ( n ) O(n) O(n);其中 n n n为二叉树节点的个数
空间复杂度:
O ( n ) O(n) O(n)
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
/**
* Lowest Common Ancestor of a Binary Tree
*
* @param root The root node of the tree
* @param p Specified node p
* @param q Specified node q
* @return TreeNode
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
return find(root, p.val, q.val);
}
/**
* @param root The root node of the tree
* @param val1 Specified value
* @param val2 Specified value
* @return TreeNode
*/
TreeNode find(TreeNode root, int val1, int val2) {
if (root == null) {
return null;
}
// Preorder position
if (root.val == val1 || root.val == val2) {
// If the target value is encountered, return it directly
return root;
}
TreeNode left = find(root.left, val1, val2);
TreeNode right = find(root.right, val1, val2);
// After the order position, it is known whether
// the left and right subtrees have a target value
if (left != null && right != null) {
// The current node is an LCA node
return root;
}
return left != null ? left : right;
}
}