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.
思路:
通过先序遍历,分别找到要查找结点(5 , 4)的路径(3->5 , 3->5->2->4),然后求路径序列中最后一个公共结点(5)即为所求。
C++:
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 private: 12 vector<TreeNode* > plist; 13 14 public: 15 void rec(TreeNode *root, TreeNode *tar, vector<TreeNode* >& res) 16 { 17 if(root == tar) 18 { 19 vector<TreeNode* >::iterator it = plist.begin(); 20 for(; it != plist.end(); it++) 21 res.push_back(*it); 22 23 return ; 24 } 25 26 if(root->left != 0) 27 { 28 plist.push_back(root->left); 29 rec(root->left, tar, res); 30 plist.pop_back(); 31 } 32 33 if(root->right != 0) 34 { 35 plist.push_back(root->right); 36 rec(root->right, tar, res); 37 plist.pop_back(); 38 } 39 } 40 41 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 42 if(root == 0) 43 return 0; 44 45 vector<TreeNode* > list1, list2; 46 47 plist.push_back(root); 48 rec(root, p, list1); 49 50 plist.clear(); 51 plist.push_back(root); 52 rec(root, q, list2); 53 54 TreeNode *ret = 0; 55 vector<TreeNode* >::iterator it1 = list1.begin(); 56 vector<TreeNode* >::iterator it2 = list2.begin(); 57 for(; it1 != list1.end() && it2 != list2.end(); it1++, it2++) 58 { 59 if(*it1 == *it2) 60 ret = *it1; 61 } 62 63 return ret; 64 } 65 };
时间: 2024-10-30 05:14:24