C++ 二叉树最近的公共祖先

已知二叉树,求二叉树中给定的两个节点的最近公共祖先。

#include<vector>
#include<stdio.h>
struct TreeNode
{
 int val;
 TreeNode* left;
 TreeNode* right;
 TreeNode(int x) : val(x), left(NULL), right(NULL){}
};
class Solution
{
public:
 Solution() {};
 ~Solution() {};
 TreeNode* lowestCommonAncestor
 (TreeNode* root, TreeNode* node_p,TreeNode *node_q)
 {
  std::vector<TreeNode*> node_p_path;
  std::vector<TreeNode*> node_q_path;
  std::vector<TreeNode*> path;
  int finish = 0;
  preorder(root,node_p,finish,path,node_p_path);
  finish = 0;
  path.clear();
  preorder(root, node_q, finish, path,node_q_path);
  int path_len = 0;
  if (node_p_path.size()<=node_q_path.size())
  {
   path_len = node_p_path.size();
  }
  else 
  {
   path_len = node_q_path.size();
  }
  TreeNode* ancestor=0;
  for (int i = 0; i < path_len; i++)
  {
   if (node_p_path[i] == node_q_path[i])
   {
    ancestor = node_p_path[i];
   }
  }
  return ancestor;
 }
private:
 void preorder(TreeNode *node,TreeNode *search, int &finish, std::vector<TreeNode*> &path,std::vector<TreeNode*> &result)
 {
  if (!node||finish)
  {
   return;
  }
  path.push_back(node);
  if (node==search)
  {
   finish = 1;
   result=path;
  }
  preorder(node->left, search, finish, path,result);
  preorder(node->right, search, finish, path,result);
  path.pop_back();
 }
};
int main()
{
 TreeNode a(3);
 TreeNode b(5);
 TreeNode c(1);
 TreeNode d(6);
 TreeNode e(2);
 TreeNode f(0);
 TreeNode x(8);
 TreeNode y(7);
 TreeNode z(4);
 a.left = &b;
 a.right = &c;
 b.left = &d;
 b.right = &e;
 c.left = &f;
 c.right = &x;
 e.left = &y;
 e.right = &z;
 Solution solve;
 TreeNode* result= solve.lowestCommonAncestor(&a,&b,&c);
 printf("%d\n",result->val);
 result = solve.lowestCommonAncestor(&a, &d, &z);
 printf("%d\n", result->val);
 result = solve.lowestCommonAncestor(&a, &b, &y);
 printf("%d\n", result->val);
 return 0;
}

运行结果为:

3
5
5
发布了61 篇原创文章 · 获赞 46 · 访问量 1580

猜你喜欢

转载自blog.csdn.net/weixin_44208324/article/details/104883988