二叉搜索树建树并且查找最低公共祖先

//============================================================================
// Name        : reversestring.cpp
// Author      : qxyu
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<string>
#include<unordered_map>
//#include<uint32_t>
using namespace std;

/**
 * Definition for a point.
 */
struct Treenode{
	Treenode* left;
	Treenode* right;

	int val;
	Treenode(int x):val(x),left(NULL),right(NULL){}
};

Treenode* insert(Treenode* root, int t){
	if(root==NULL)
	{
		Treenode* p = new Treenode(t);
		root=p;
		return root;
	}
	else if(t>root->val){
		root->right=insert(root->right,t);
	}
	else
		root->left=insert(root->left,t);
	return root;
}

Treenode* build_tree(vector<int>& input){
	Treenode* root=new Treenode(input[0]);
	for(int i = 1; i < input.size(); i ++){
		insert(root,input[i]);
	}
	return root;
}



Treenode* getFirstParent(Treenode* p1, Treenode* p2, Treenode* root){
	if(p1==NULL||p2==NULL||root==NULL) return NULL;
	if(p1->val < root->val && p2->val < root->val)
		return getFirstParent(p1, p2, root->left);
	else if(p1->val > root->val && p2->val > root->val)
		return getFirstParent(p1, p2, root->right);
	else
		return root;
}
int main()
{
   vector<int> v;
   v.push_back(4);
   v.push_back(3);
   v.push_back(1);
   v.push_back(2);
   v.push_back(7);
   v.push_back(6);

   Treenode* root=build_tree(v);
   Treenode* a=root->left->left;
  // cout<<a->val;
   Treenode* b=root->right;

  Treenode* t=  getFirstParent(a,b,root);
  cout<<t->val;
  return 0;

}

其中insert函数也可以这样写
<pre name="code" class="cpp">void insert(Treenode*& root, int t){
	if(root==NULL)
	{
		Treenode* p = new Treenode(t);
		root=p;

	}
	else if(t>root->val){
		insert(root->right,t);
	}
	else
		insert(root->left,t);

}

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/womanonthetr/article/details/52161823
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞