本文共 1826 字,大约阅读时间需要 6 分钟。
???????????????????????????????????????????????????????????????
??????????????????
#includeusing namespace std;class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { vector path_p = getPath(root, p); vector path_q = getPath(root, q); return findLastCommonAncestor(path_p, path_q); } vector getPath(TreeNode* node, TreeNode* target) { vector path; while (node != null && node != target) { path.push_back(node); if (node->left != null && node->left->val == target->val) { node = node->left; } else if (node->right != null && node->right->val == target->val) { node = node->right; } else { return path; } } if (node != null) { path.push_back(node); } return path; } TreeNode* findLastCommonAncestor(const vector & path_p, const vector & path_q) { int i = 0, j = 0; int len = 0; TreeNode* last = null; while (i < path_p.size() && j < path_q.size()) { if (path_p[i]->val == path_q[j]->val) { if (last != path_p[i]) { last = path_p[i]; } len++; i++; j++; } else { if (i < j) { i++; } else { j++; } } } return last; }};
getPath??????????????????findLastCommonAncestor??????????????????????????????????????????????????O(h)?????????????????h??????
转载地址:http://hztf.baihongyu.com/