码迷,mamicode.com
首页 > 其他好文 > 详细

CC150 4.6

时间:2014-11-27 08:02:42      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:interview

4.6 Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.


BT

Node find(Node n, Node a, Node b)
{
  if (n == a || n == b)
  {
    return n; 
  }
  
  int nodeMatch = nodeMatch(a.left);
  if (nodeMatch == 0)
    return find(n.right, a, b);
  else if (nodeMatch == 1)
    return n;
  else
    return find(r.left, a, b);
}


int nodeMatch(Node n, Node a, Node b)
{
  if (n == null)
    return 0;
  
  int toReturn = 0;
  if (n == a || n == b)
    toReturn ++;
  toReturn += find(n.left) + find(n.right);
}


CC150 4.6

标签:interview

原文地址:http://7371901.blog.51cto.com/7361901/1583045

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!