LeetCode 236 最近公共祖先

题目:找p和q的最近公共祖先

理解:

当遍历到一个root点的时候,

1.判断root是不是null如果root为null,那么就无所谓祖先节点,直接返回null就好了

2.如果root的左子树存在p,右子树存在q,那么root肯定就是最近祖先

3.如果pq都在root的左子树,那么就需要递归root的左子树,右子树同理

 

代码:

 1 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
 2     if(root == NULL || root == p || root ==q) return root;
 3     TreeNode* left = lowestCommonAncestor(root->left, p, q);
 4     TreeNode* right = lowestCommonAncestor(root->right, p, q);
 5     if(left && right){
 6         return root;
 7     }else{
 8         return left == NULL ? right : left;
 9     }
10 }

 

posted @ 2015-12-03 09:54  Acker  阅读(4671)  评论(0编辑  收藏  举报