思想就是层次遍历,然后判断每个节点是否为父节点、
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool judge(struct TreeNode* root,struct TreeNode* q){
if(!root) return false;
if(root==q) return true;
return judge(root->left,q)||judge(root->right,q);
}
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
if(root==p||root==q) return root;
if(judge(p,q)) return p;
if(judge(q,p)) return q;
struct TreeNode* queue[5000];
int front=0,tail=0;
queue[tail++]=root;
struct TreeNode* x=root;
while(front!=tail){
struct TreeNode* temp=queue[front++];
if(temp==q||temp==p) break;
if(judge(temp,p)&&judge(temp,q)) x=temp;
if(temp->left) queue[tail++]=temp->left;
if(temp->right) queue[tail++]=temp->right;
}
return x;
}
结果:
标签:TreeNode,struct,temp,祖先,二叉树,judge,return,236,root From: https://www.cnblogs.com/llllmz/p/18057386