方法一:bottom-up
Node *LCA(Node *root, Node *p, Node *q) { if (!root) return NULL; if (root == p || root == q) return root; Node *left = LCA(root->left, p, q); Node *right = LCA(root->right, p, q); if (left && right) return root; // if p and q are on both sides return left ? left :right ; // either one of p,q is on one side OR p,q is not in L&R subtrees }
方法二:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root==NULL||p==NULL||q==NULL) return NULL; vector<TreeNode*>s1; vector<TreeNode*>s2; bool left=findpath(root,p,s1); bool right=findpath(root,q,s2); int i; if(left&&right){ for( i=0;i<s1.size()&&i<s2.size();i++){ if(s1[i]!=s2[i]) break; } return s1[i-1]; } else return NULL; } bool findpath(TreeNode*root,TreeNode*p,vector<TreeNode*>&s1){ TreeNode*cur=root; TreeNode*prev=NULL; while(cur!=NULL||!s1.empty()){ while(cur!=NULL){ s1.push_back(cur); cur=cur->left; } cur=s1.back(); if(cur->right==NULL||cur->right==prev){ if(cur==p){ return true; } prev=cur; cur=NULL; s1.pop_back(); } else cur=cur->right; } return false; }
方法三:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root==NULL||p==NULL||q==NULL) return NULL; vector<TreeNode*>s1; vector<TreeNode*>s2; bool left=findpath(root,p,s1); bool right=findpath(root,q,s2); int i; if(left&&right){ for( i=0;i<s1.size()&&i<s2.size();i++){ if(s1[i]!=s2[i]) break; } return s1[i-1]; } else return NULL; } bool findpath(TreeNode*root,TreeNode*p,vector<TreeNode*>&s){ if(root==NULL) return false; s.push_back(root); if(root==p) return true; bool left=findpath(root->left,p,s); bool right=findpath(root->right,p,s); if(left||right) return true; s.pop_back(); return false; }
原文:http://www.cnblogs.com/kkshaq/p/4662840.html