题目描述
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
解题思路
最直观的方法就是用一个数组存储在树中到达p与q的路径,然后再逐一比较找出最后一个公共节点
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/class Solution {public:bool get_path(TreeNode* root, TreeNode* target, vector<TreeNode*> &path) {if (root==NULL)return false;if (root==target) {path.push_back(root);return true;}path.push_back(root);if (get_path(root->left, target, path))return true;else {if (get_path(root->right, target, path))return true;else {path.pop_back();return false;}}}TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {vector<TreeNode*> path_p, path_q;get_path(root, p, path_p);get_path(root, q, path_q);int i=0;while (i<path_p.size() && i<path_q.size() && path_p[i] == path_q[i])i++;return path_p[i-1];}};
另一种方法更加的优雅且空间复杂度低,具体来说,我们定义一个函数find_node,它用于判断从当前节点出发能否找到p节点和q节点,具体来说就是:
- lres=find_node(curr->left, p, q)
- rres=find_node(curr->right, p, q)
那么,如果lres && rres,说明curr就是公共祖先,或者(lres ||rres) && (curr->val==p->val ||curr->val==q->val),也是说明curr就是公共祖先
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/class Solution {public:TreeNode* tgt;bool find_node(TreeNode* curr, TreeNode* p, TreeNode* q) {if (curr==NULL)return false;bool lres = find_node(curr->left, p, q);bool rres = find_node(curr->right, p, q);if (lres && rres || (curr->val == p->val || curr->val == q->val) && (lres || rres))tgt = curr;return lres ||rres || curr->val == p->val || curr->val == q->val;}TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {find_node(root, p, q);return tgt;}};
