“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)”。给出两个节点找到二叉树的公共节点,下图中而可以发现,给出节点5,1,最近公共节点是3。
直接给出代码。
/**
* 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) {
//返回的结构主要就是公共节点,p或者q还有空节点
if(root == NULL) //访问到叶节点直接返回NULL
return root;
if(root == p || root == q) //访问到p或者q返回公共节点
return root;
// 这里的left和right也存在4种可能,NULL,p,q或者公共节点
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p ,q);
//左右都不为空找到了公共节点直接返回
if(left != NULL && right != NULL)
return root;
//后面就是NULL节点或者p和q节点
else if(left != NULL)
return left;
else if(right != NULL)
return right;
return NULL;
}
};