LeetCode-Lowest Common Ancestor of a Binary Tre

LiBlog發表於2016-08-21

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.

 
 Solution:
 1 /**
 2  * Definition for a binary tree node. public class TreeNode { int val; TreeNode
 3  * left; TreeNode right; TreeNode(int x) { val = x; } }
 4  */
 5 public class Solution {
 6     public class Result {
 7         boolean findP, findQ;
 8         TreeNode ancestor;
 9 
10         public Result(boolean p, boolean q) {
11             findP = p;
12             findQ = q;
13             ancestor = null;
14         }
15     }
16 
17     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
18         return findAncestorRecur(root, p, q).ancestor;
19     }
20 
21     public Result findAncestorRecur(TreeNode cur, TreeNode p, TreeNode q) {
22         if (cur == null) {
23             return new Result(false, false);
24         }
25 
26         boolean findP = (cur == p), findQ = (cur == q);
27         Result leftRes = findAncestorRecur(cur.left, p, q);
28         if (leftRes.ancestor != null)
29             return leftRes;
30         Result rightRes = findAncestorRecur(cur.right, p, q);
31         if (rightRes.ancestor != null)
32             return rightRes;
33 
34         findP = (findP || leftRes.findP || rightRes.findP);
35         findQ = (findQ || leftRes.findQ || rightRes.findQ);
36 
37         Result res = new Result(findP, findQ);
38         if (findP && findQ)
39             res.ancestor = cur;
40 
41         return res;
42     }
43 }

 

相關文章