代码实现:
思路:
递归判断左子树和右子树,查找p或者q是否在当前节点的子树上
1,在同一子树上,同一左子树,返回第一个找到的相同值,同一右子树上,返回第一个找到的相同值
2,不在同一子树是,说明当前节点就是他们的公共祖先节点/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ struct TreeNode* lowestCommonAncestor(struct TreeNode *root, struct TreeNode *p, struct TreeNode *q) { if (p == root || q == root || root == NULL) { return root; } struct TreeNode *l = lowestCommonAncestor(root->left, p, q); struct TreeNode *r = lowestCommonAncestor(root->right, p, q); if (l != NULL && r != NULL) { return root; } if (l == NULL && r != NULL) { return r; } else if (l != NULL && r == NULL) { return l; } else { return NULL; } }