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.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
13         if(root==NULL||p==NULL||q==NULL)
14           return NULL;
15         return FindLCA(root,p,q);
16     }
17 
18 private:
19     TreeNode* FindLCA(TreeNode* root, TreeNode* p, TreeNode* q){
20         if(root==NULL)
21             return NULL;
22         if(root==p||root==q)
23           return root;
24         TreeNode* left;
25         TreeNode* right;
26         left=FindLCA(root->left,p,q);
27         right=FindLCA(root->right,p,q);
28         if(left&&right)
29           return root;
30         return left?left:right;
31         }  
32     
33 };

 

posted @ 2015-07-23 12:23  鸭子船长  阅读(209)  评论(0编辑  收藏  举报