Lowest Common Ancestor of a Binary Tree II

Given the root of a binary tree, return the lowest common ancestor (LCA) of two given nodes, p and q. If either node p or q does not exist in the tree, return null. All values of the nodes in the tree are unique.

According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p and q in a binary tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)". A descendant of a node x is a node y that is on the path from node x to some leaf node.

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

思路:这题跟 Lowest Common Ancestor of a Binary Tree_leetcode 解题思路-CSDN博客 的区别是,这题如果其中一个node不在tree里面,就要返回null,所以要去搜索整个tree,然后用全局变量去记录是否visit过p和q,然后才能返回LCA,否则就是返回null;其余代码跟上面LCA一模一样

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private boolean pfind = false;
    private boolean qfind = false;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode LCA = findLCA(root, p, q);
        return pfind && qfind ? LCA : null;
    }
    
    private TreeNode findLCA(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return root;
        }
        TreeNode leftnode = findLCA(root.left, p, q);
        TreeNode rightnode = findLCA(root.right, p, q);
        // 一定要上面的dfs运行完,搜索完整个tree了,才做判断,因为要去在整个tree里面搜p,q
        // 下面的部分不能提前,否则没办法搜整个tree;
        if(root == p) {
            pfind = true;
            return root;
        }
        if(root == q) {
            qfind = true;
            return root;
        }
        if(leftnode == null) {
            return rightnode;
        } else if(rightnode == null) {
            return leftnode; 
        } else {
            return root;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值