算法—— 最近公共祖先 III

给一棵二叉树和二叉树中的两个节点,找到这两个节点的最近公共祖先LCA。
两个节点的最近公共祖先,是指两个节点的所有父亲节点中(包括这两个节点),离这两个节点最近的公共的节点。
返回 null 如果两个节点在这棵树上不存在最近公共祖先的话。
样例
样例1
输入:
{4, 3, 7, #, #, 5, 6}
3 5
5 6
6 7
5 8
输出:
4
7
7
null
解释:
4
/ \
3 7
. . / \
. . 5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
LCA(5, 8) = null

实现:

public class Solution {
    /*
     * @param root: The root of the binary tree.
     * @param A: A TreeNode
     * @param B: A TreeNode
     * @return: Return the LCA of the two nodes.
     */

    public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode A, TreeNode B) {
        // write your code here
        boolean existA = isNodeInTree(root, A);
        boolean existB = isNodeInTree(root, B);
         if (!existA || !existB) {
            return null;
        }
        return getLowestAncestor(root,A,B);
    }
    
    public TreeNode getLowestAncestor(TreeNode root, TreeNode A, TreeNode B){
        if (root == null || A == null || B == null) return null;
        if (root == A || root == B) return root;
        TreeNode left =  getLowestAncestor(root.left, A, B);
        TreeNode right = getLowestAncestor(root.right, A, B);
        if (left != null && right != null) {
            return root;
        }

        if (left != null) {
            return left;
        }
        if (right != null) {
            return right;
        }
        return null;
        
    }
     private  boolean isNodeInTree(TreeNode root, TreeNode node) {
        if (root == null || node == null) return false;
        if (root == node) return true;
        boolean left = isNodeInTree(root.left, node);
        boolean right = isNodeInTree(root.right, node);
        return left || right;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值