二叉树中 找两个结点的最近的公共祖先结点
#pragma once
#include <iostream>
using namespace std;
struct Node
{
Node * left;
Node * right;
int value;
Node( int v )
:value( v )
, left( NULL )
, right( NULL )
{}
};
int _find_ancestor(Node * root, Node* & ancestor , const Node* a, const Node* b)
{
if (root == NULL)
{
return 0;
}
int count = 0;
count += _find_ancestor( root ->left, ancestor , a, b);
if (root == a || root == b )
{
count += 1;
}
count += _find_ancestor( root ->right, ancestor , a, b);
if (count == 2)
{
ancestor = root ;
count = 0; //防止返回时,上面const的值还是2,导致anceator不准确被覆盖
}
return count;
}
void test_find_ancestor()
{
Node n1(1);
Node n2(2);
Node n3(3);
Node n4(4);
Node n5(5);
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n2.right = &n5;
Node * ancestor = NULL ;
_find_ancestor(&n1, ancestor, &n4, &n5);
_find_ancestor(&n1, ancestor, &n2, &n5);
_find_ancestor(&n1, ancestor, &n5, &n3);
}
int main()
{
test_find_ancestor();
getchar();
return 0;
}
bool Find(Node* _root,Node* data)
{
if (_root == NULL)
{
return false;
}
Node* cur = _root;
while (cur)
{
if (data < cur)
{
cur = cur->_left;
}
else if (data > cur)
{
cur = cur->_right;
}
else
{
return true;
}
}
return true;
}
//O(N^2)
Node* GetCommonRoot(Node* root, Node* x1, Node* x2)
{
assert(x1&&x2);
if (root = NULL)
{
return NULL;
}
if (x1 == root || x2 == root)
{
return root;
}
bool x1InLeft = Find(root->_left, x1);
bool x2InRight = Find(root->_right, x2);
if (x1InLeft&& x2InRight)
return root;
bool x2InLeft = Find(root->_left, x2);
bool x1InRight = Find(root->_right,x1);
if (x2InLeft && x1InRight)
return root;
if (x1InRight && x2InLeft)
{
return GetCommonRoot(root->_left, x1, x2);
}
else if (x1InRight && x2InRight)
{
return GetCommonRoot(root->_right, x1, x2);
}
else
{
assert(false);
return (NULL);
}
}
bool GetPath(Node* root, Node* x, vector<Node*> paths)
{
assert(x);
if (root == NULL)
return false;
//stack 栈
paths.push_back(root);
if (root == x)
return true;
if (GetPath(root->_left, x, paths))
return true;
if (GetPath(root->_right, x, paths))
return true;
paths.pop_back();
return false;
}