力扣236. 二叉树的最近公共祖先

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;
    }
}
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值