最近共同祖先


#include <iostream>
#include <vector>
using namespace std;

// 参考 http://blog.csdn.net/cxllyg/article/details/7635992
// 参考 《剑指offer》P256

struct node{
  int data;
  node *left;
  node *right;

  node(const int &x, node *l = NULL, node *r = NULL){
    data = x;
    left = l;
    right = r;
  }
  ~node(){}
};

bool node_path(node *p, node *root, vector<node *> &path){
  if(root == NULL)
    return false;

  if(p == root){
    path.push_back(root);
    return true;
  }

  // 倒序保存
  //if(node_path(p, root->left, path)){
  //  path.push_back(root);
  //  return true;
  //}
  //else if(node_path(p, root->right, path)){
  //  path.push_back(root);
  //  return true;
  //}
  //else {
  //  return false;
  //}

  // 顺序保存
  path.push_back(root);
  bool found = false;
  if(node_path(p, root->left, path)){
    found = true;
  }
  else if(node_path(p, root->right, path)){
    found = true;
  }
  else {
    found = false;
  }
  if(!found){
    path.pop_back();
  }
  return found;
}

node *find_lowest_common_ancestor(node *p1, node *p2, node *root){
  vector<node *> path1, path2;
  bool find1 = node_path(p1, root, path1);
  bool find2 = node_path(p2, root, path2);
  if(!(find1 && find2))
    return NULL;
  node *ancestor = root;
  // 倒序取最近共同祖先
  //int max_common_len = path1.size() < path2.size() ? path1.size() : path2.size();
  //for(int i = 0; i < max_common_len; ++i){
  //  if(path1[path1.size() - 1 - i] != path2[path2.size() - 1 - i])
  //    break;
  //  ancestor = path1[path1.size() - 1 - i];
  //}
  // 顺序取最近共同祖先
  int max_common_len = path1.size() < path2.size() ? path1.size() : path2.size();
  for(int i = 0; i < max_common_len; ++i){
    if(path1[i] != path2[i])
      break;
    ancestor = path1[i];
  }
  return ancestor;
}

int main(){
  node *tmp;
  node *p1;
  node *p2;

  node *root = new node(1);
  tmp = new node(2);
  root->left = tmp;
  tmp = new node(3);
  root->right = tmp;
  tmp = new node(4);
  root->left->left = tmp;
  tmp =  new node(5);
  root->left->right = tmp;
  tmp = new node(6);
  p1 = tmp;
  root->left->left->left = tmp;
  tmp = new node(7);
  root->left->left->right = tmp;
  tmp = new node(8);
  p2 = tmp;
  root->left->right->left = tmp;
  tmp = new node(9);
  root->left->right->right = tmp;

  node *ancestor = find_lowest_common_ancestor(p1, p2, root);
  cout << "ancestor: " <<ancestor->data << endl;

  int ttt = 0;
  return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值