写在前面
“不要在同一个地方摔倒两次。”
本题是做过的题目,再次遇到还是在同样的地方摔倒。总结没做出来的原因,主要还是对递归的理解不够深刻,导致思路混乱。
题目描述
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.
思路分析
一个典型的二叉树递归查找的题目。我的思路是困在不知道如何递归向上,事实上先序遍历已经自动处理这个情况了,根据题意,我们知道,只有两种情况需要考虑,一种就是p或q是另外一个结点的子节点,一种就是两者属于同一棵树的子节点,现在就是要找出这颗树的根节点。很明显我们要用先序遍历来解决这个问题(可以利用自底向上的递归结果),如果是第一种情况,很明显,我们先遍历到的节点一定是另一节点的父节点;如果是第二种情况,那么必然在某一轮的递归中找到该父节点(向上过程),最终先序遍历的完整返回结果就是我们要找的ancestor。
代码实现
/**
* 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr||root == p || root == q) return root;
auto left = lowestCommonAncestor(root->left,p,q);
auto right = lowestCommonAncestor(root->right,p,q);
if(left&&right) return root;
return left==nullptr?right:left;
}
};