算法系列——Lowest Common Ancestor of a Binary Tree

题目描述

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

解题思路

这道题目和Lowest Common Ancestor of a Binary Search Tree
类似,只不过现在条件变为一颗普通的二叉树,要求出最低公共祖先。

首先要先确定给的两个node是否都在tree里,如果都在tree里的话,就可以分成3种情况,第一种情况是两个节点是在公共祖先的左右两侧,第二种情况是都在树的左侧,第三种情况是都在树的右侧,如果是第二,第三种情况的话,公共祖先就在给定的两个点中比较上面的那一个。

如果转换成代码的话,从上往下走,base case分为3种,判断遇到了p就直接返回p,遇到q就直接返回q,不用向下做了。如果left,right都不为空,就返回root自己;left,right哪一个不为空就返回哪个,整个recursion做完就可以得到LCA。

程序实现

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root == null) return null;
    if(root == p) return p;
    if(root == q) return q;

    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);

    if(left != null && right != null) return root;
    return left != null ? left : right;
}

你可能感兴趣的:(算法,算法系列)