首页 > 其他 > 详细

236. Lowest Common Ancestor of a Binary Tree

时间:2017-02-03 10:46:56      阅读:350      评论:0      收藏:0      [点我收藏+]

236. Lowest Common Ancestor of a Binary Tree

  • Total Accepted: 82386
  • Total Submissions: 280908
  • Difficulty: Medium
  • Contributors: Admin

 

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______3______
       /                  ___5__          ___1__
   /      \        /         6      _2       0       8
         /           7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

DFS:

1. Base Case: 一般是找到符合条件的

2. recursive: 调用本身

3. Judgement: 一般是排除不符合条件的

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
13         //在二叉树中来搜索p和q,然后从路径中找到最后一个相同的节点即为父节点,我们可以用递归来实现
14         //base case
15         if(!root || root == p || root == q) return root;
16         //recursive
17         TreeNode* left = lowestCommonAncestor(root -> left, p, q);
18         TreeNode* right = lowestCommonAncestor(root -> right, p, q);
19         //judgement
20         if(left && right) return root;//如果一个在左子树 一个在右子树 return root
21         return left ? left : right;//如果left不为空 return left 反之返回right
22     }
23 };

 

 

 

 

 

 

 

 

236. Lowest Common Ancestor of a Binary Tree

原文:http://www.cnblogs.com/93scarlett/p/6362001.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!