Lowest Common Ancestor in a Binary Tree (二叉树中两个节点的最近公共祖先)

Given a binary tree (not a binary search tree) and two values say n1 and n2, write a program to find the least common ancestor.

Following is definition of LCA from Wikipedia: Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself).

The LCA of n1 and n2 in T is the shared ancestor of n1 and n2 that is located farthest from the root. Computation of lowest common ancestors may be useful, for instance, as part of a procedure for determining the distance between pairs of nodes in a tree: the distance from n1 to n2 can be computed as the distance from the root to n1, plus the distance from the root to n2, minus twice the distance from the root to their lowest common ancestor. (Source Wiki)

lca

We have discussed an efficient solution to find LCA in Binary Search Tree.  In Binary Search Tree, using BST properties, we can find LCA in O(h) time where h is height of tree.  Such an implementation is not possible in Binary Tree as keys Binary Tree nodes don’t follow any order. Following are different approaches to find LCA in Binary Tree.

Method 1 (By Storing root to n1 and root to n2 paths): Following is simple O(n) algorithm to find LCA of n1 and n2. 1) Find path from root to n1 and store it in a vector or array. 2) Find path from root to n2 and store it in another vector or array. 3) Traverse both paths till the values in arrays are same. Return the common element just before the mismatch. 

Following is C++ implementation of above algorithm.

 

 1 // A O(n) solution to find LCA of two given values n1 and n2
 2 #include <iostream>
 3 #include <vector>
 4 using namespace std;
 5  
 6 // A Bianry Tree node
 7 struct Node
 8 {
 9     int key;
10     struct Node *left, *right;
11 };
12  
13 // Utility function creates a new binary tree node with given key
14 Node * newNode(int k)
15 {
16     Node *temp = new Node;
17     temp->key = k;
18     temp->left = temp->right = NULL;
19     return temp;
20 }
21  
22 // Finds the path from root node to given root of the tree, Stores the
23 // path in a vector path[], returns true if path exists otherwise false
24 bool findPath(Node *root, vector<int> &path, int k)
25 {
26     // base case
27     if (root == NULL) return false;
28  
29     // Store this node in path vector. The node will be removed if
30     // not in path from root to k
31     path.push_back(root->key);
32  
33     // See if the k is same as root's key
34     if (root->key == k)
35         return true;
36  
37     // Check if k is found in left or right sub-tree
38     if ( (root->left && findPath(root->left, path, k)) ||
39          (root->right && findPath(root->right, path, k)) )
40         return true;
41  
42     // If not present in subtree rooted with root, remove root from
43     // path[] and return false
44     path.pop_back();
45     return false;
46 }
47  
48 // Returns LCA if node n1, n2 are present in the given binary tree,
49 // otherwise return -1
50 int findLCA(Node *root, int n1, int n2)
51 {
52     // to store paths to n1 and n2 from the root
53     vector<int> path1, path2;
54  
55     // Find paths from root to n1 and root to n1. If either n1 or n2
56     // is not present, return -1
57     if ( !findPath(root, path1, n1) || !findPath(root, path2, n2))
58           return -1;
59  
60     /* Compare the paths to get the first different value */
61     int i;
62     for (i = 0; i < path1.size() && i < path2.size() ; i++)
63         if (path1[i] != path2[i])
64             break;
65     return path1[i-1];
66 }
67  
68 // Driver program to test above functions
69 int main()
70 {
71     // Let us create the Binary Tree shown in above diagram.
72     Node * root = newNode(1);
73     root->left = newNode(2);
74     root->right = newNode(3);
75     root->left->left = newNode(4);
76     root->left->right = newNode(5);
77     root->right->left = newNode(6);
78     root->right->right = newNode(7);
79     cout << "LCA(4, 5) = " << findLCA(root, 4, 5);
80     cout << "\nLCA(4, 6) = " << findLCA(root, 4, 6);
81     cout << "\nLCA(3, 4) = " << findLCA(root, 3, 4);
82     cout << "\nLCA(2, 4) = " << findLCA(root, 2, 4);
83     return 0;
84 }

Output:

LCA(4, 5) = 2
LCA(4, 6) = 1
LCA(3, 4) = 1
LCA(2, 4) = 2 

 

Time Complexity: Time complexity of the above solution is O(n). The tree is traversed twice, and then path arrays are compared.

 

Method 2 (Using Single Traversal)
The method 1 finds LCA in O(n) time, but requires three tree traversals plus extra spaces for path arrays. If we assume that the keys n1 and n2 are present in Binary Tree, we can find LCA using single traversal of Binary Tree and without extra storage for path arrays.
The idea is to traverse the tree starting from root.  If any of the given keys (n1 and n2) matches with root, then root is LCA (assuming that both keys are present).  If root doesn’t match with any of the keys, we recur for left and right subtree.   The node which has one key present in its left subtree and the other key present in right subtree is the LCA.  If both keys lie in left subtree, then left subtree has LCA also, otherwise LCA lies in right subtree.

 1 /* Program to find LCA of n1 and n2 using one traversal of Binary Tree */
 2 #include <iostream>
 3 using namespace std;
 4  
 5 // A Binary Tree Node
 6 struct Node
 7 {
 8     struct Node *left, *right;
 9     int key;
10 };
11  
12 // Utility function to create a new tree Node
13 Node* newNode(int key)
14 {
15     Node *temp = new Node;
16     temp->key = key;
17     temp->left = temp->right = NULL;
18     return temp;
19 }
20  
21 // This function returns pointer to LCA of two given values n1 and n2.
22 // This function assumes that n1 and n2 are present in Binary Tree
23 struct Node *findLCA(struct Node* root, int n1, int n2)
24 {
25     // Base case
26     if (root == NULL) return NULL;
27  
28     // If either n1 or n2 matches with root's key, report
29     // the presence by returning root (Note that if a key is
30     // ancestor of other, then the ancestor key becomes LCA
31     if (root->key == n1 || root->key == n2)
32         return root;
33  
34     // Look for keys in left and right subtrees
35     Node *left_lca  = findLCA(root->left, n1, n2);
36     Node *right_lca = findLCA(root->right, n1, n2);
37  
38     // If both of the above calls return Non-NULL, then one key
39     // is present in once subtree and other is present in other,
40     // So this node is the LCA
41     if (left_lca && right_lca)  return root;
42  
43     // Otherwise check if left subtree or right subtree is LCA
44     return (left_lca != NULL)? left_lca: right_lca;
45 }
46  
47 // Driver program to test above functions
48 int main()
49 {
50     // Let us create binary tree given in the above example
51     Node * root = newNode(1);
52     root->left = newNode(2);
53     root->right = newNode(3);
54     root->left->left = newNode(4);
55     root->left->right = newNode(5);
56     root->right->left = newNode(6);
57     root->right->right = newNode(7);
58     cout << "LCA(4, 5) = " << findLCA(root, 4, 5)->key;
59     cout << "\nLCA(4, 6) = " << findLCA(root, 4, 6)->key;
60     cout << "\nLCA(3, 4) = " << findLCA(root, 3, 4)->key;
61     cout << "\nLCA(2, 4) = " << findLCA(root, 2, 4)->key;
62     return 0;
63 }
64  

Output:

LCA(4, 5) = 2
LCA(4, 6) = 1
LCA(3, 4) = 1
LCA(2, 4) = 2 

Thanks to Atul Singh for suggesting this solution.

Time Complexity: Time complexity of the above solution is O(n) as the method does a simple tree traversal in bottom up fashion.

 

Note that the above method assumes that keys are present in Binary Tree.  If one key is present and other is absent, then it returns the present key as LCA (Ideally should have returned NULL). We can extend this method to handle all cases by passing two boolean variables v1 and v2.  v1 is set as true when n1 is present in tree and v2 is set as true if n2 is present in tree.

  1 /* Program to find LCA of n1 and n2 using one traversal of Binary Tree.
  2    It handles all cases even when n1 or n2 is not there in Binary Tree */
  3 #include <iostream>
  4 using namespace std;
  5  
  6 // A Binary Tree Node
  7 struct Node
  8 {
  9     struct Node *left, *right;
 10     int key;
 11 };
 12  
 13 // Utility function to create a new tree Node
 14 Node* newNode(int key)
 15 {
 16     Node *temp = new Node;
 17     temp->key = key;
 18     temp->left = temp->right = NULL;
 19     return temp;
 20 }
 21  
 22 // This function returns pointer to LCA of two given values n1 and n2.
 23 // v1 is set as true by this function if n1 is found
 24 // v2 is set as true by this function if n2 is found
 25 struct Node *findLCAUtil(struct Node* root, int n1, int n2, bool &v1, bool &v2)
 26 {
 27     // Base case
 28     if (root == NULL) return NULL;
 29  
 30     // If either n1 or n2 matches with root's key, report the presence
 31     // by setting v1 or v2 as true and return root (Note that if a key
 32     // is ancestor of other, then the ancestor key becomes LCA)
 33     if (root->key == n1)
 34     {
 35         v1 = true;
 36         return root;
 37     }
 38     if (root->key == n2)
 39     {
 40         v2 = true;
 41         return root;
 42     }
 43  
 44     // Look for keys in left and right subtrees
 45     Node *left_lca  = findLCAUtil(root->left, n1, n2, v1, v2);
 46     Node *right_lca = findLCAUtil(root->right, n1, n2, v1, v2);
 47  
 48     // If both of the above calls return Non-NULL, then one key
 49     // is present in once subtree and other is present in other,
 50     // So this node is the LCA
 51     if (left_lca && right_lca)  return root;
 52  
 53     // Otherwise check if left subtree or right subtree is LCA
 54     return (left_lca != NULL)? left_lca: right_lca;
 55 }
 56  
 57 // Returns true if key k is present in tree rooted with root
 58 bool find(Node *root, int k)
 59 {
 60     // Base Case
 61     if (root == NULL)
 62         return false;
 63  
 64     // If key is present at root, or in left subtree or right subtree,
 65     // return true;
 66     if (root->key == k || find(root->left, k) ||  find(root->right, k))
 67         return true;
 68  
 69     // Else return false
 70     return false;
 71 }
 72  
 73 // This function returns LCA of n1 and n2 only if both n1 and n2 are present
 74 // in tree, otherwise returns NULL;
 75 Node *findLCA(Node *root, int n1, int n2)
 76 {
 77     // Initialize n1 and n2 as not visited
 78     bool v1 = false, v2 = false;
 79  
 80     // Find lca of n1 and n2 using the technique discussed above
 81     Node *lca = findLCAUtil(root, n1, n2, v1, v2);
 82  
 83     // Return LCA only if both n1 and n2 are present in tree
 84     if (v1 && v2 || v1 && find(lca, n2) || v2 && find(lca, n1))
 85         return lca;
 86  
 87     // Else return NULL
 88     return NULL;
 89 }
 90  
 91 // Driver program to test above functions
 92 int main()
 93 {
 94     // Let us create binary tree given in the above example
 95     Node * root = newNode(1);
 96     root->left = newNode(2);
 97     root->right = newNode(3);
 98     root->left->left = newNode(4);
 99     root->left->right = newNode(5);
100     root->right->left = newNode(6);
101     root->right->right = newNode(7);
102     Node *lca =  findLCA(root, 4, 5);
103     if (lca != NULL)
104        cout << "LCA(4, 5) = " << lca->key;
105     else
106        cout << "Keys are not present ";
107  
108     lca =  findLCA(root, 4, 10);
109     if (lca != NULL)
110        cout << "\nLCA(4, 10) = " << lca->key;
111     else
112        cout << "\nKeys are not present ";
113  
114     return 0;
115 }

Output:

LCA(4, 5) = 2
Keys are not present 

 

posted @ 2016-07-30 19:27  琴影  阅读(310)  评论(0)    收藏  举报