int postOrder(TreeNode* root, TreeNode* p, TreeNode* q, TreeNode *&ans){
if (!root) {
return 0;
}
// 查看子结点的梳计个数
int lcnt = postOrder(root->left, p, q, ans);
int rcnt = postOrder(root->right, p, q, ans);
// 利用子结点返回的信息来进行处理
// 如果左边有一个,右边有一个,那么当前root就是最低公共祖先
if (lcnt == 1 && rcnt ==1) {
ans = root;
}else if(lcnt ==1 || rcnt ==1){
// 如果左边找到一个,或者右边找到一个
// 并且我等于其中某一个结点p|q
// 那么当前root就是最低公共祖先
if (root == p || root == q) {
ans = root;
}
}
// 返回值为以root为根的子树, 统计里面的p,q结点的个数。
return lcnt + rcnt + ((root ==p || root ==q)? 1 : 0);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode *ans = nullptr;
postOrder(root, p, q, ans);
return ans;
}
递归
/**
* 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) return NULL;
if(p == root|| q == root) return root;
TreeNode *l = lowestCommonAncestor(root->left,p,q);
TreeNode *r = lowestCommonAncestor(root->right,p,q);
if(!l) return r;
if(!r) return l;
if(l && r) return root;
return NULL;
}
};