/*
1) node1是node2的祖先节点或孩子节点,
可以理解为两个节点在一条线上。 例如:Dist(2,4), Dist(6,1)
2) node1 和 node2 没有直接或间接的父子关系。
例如,Dist(4,3), 他们需要一个共同的祖先节点1 连接起来
Dist(n1, n2) = Dist(root, n1) + Dist(root, n2) - 2*Dist(root, lca)
*/
#include<iostream>
using namespace std;
struct Node{
int data;
Node *lchild;
Node *rchild;
};
int max(int a,int b)
{
return a>b?a:b;
}
Node *getPublicParetnNode(Node *root,int n1,int n2)
{
if(root==NULL) return NULL;
if(root->data==n1||root->data==n2)
return root;
Node *lNode=getPublicParetnNode(root->lchild,n1,n2);
Node *rNode=getPublicParetnNode(root->rchild,n1,n2);
if(!lNode&&!rNode) return NULL;
else if(lNode&&rNode) return root;
else return lNode==NULL?rNode:lNode;
}
int getDistanceToRoot(Node *root,int n)
{
if(root==NULL)return -1;
if(root->data==n) return 0;
int level=getDistanceToRoot(root->lchild,n);
if(level==-1)//表示左子树上没有。
level=getDistanceToRoot(root->rchild,n);
if(level!=-1)
return level+1;
return -1;
}
void buildTree(Node *&root)
{
int num;
scanf("%d",&num);
if(num==0)
{
root=NULL;
return;
}
root=new Node;
root->data=num;
buildTree(root->lchild);
buildTree(root->rchild);
}
int getTwoNodeDis(Node *root,int n1,int n2)
{
int d1=getDistanceToRoot(root,n1);
int d2=getDistanceToRoot(root,n2);
Node *node=getPublicParetnNode(root,n1,n2);
int d3=getDistanceToRoot(root,node);
return d1+d2-2*d3;
}
1) node1是node2的祖先节点或孩子节点,
可以理解为两个节点在一条线上。 例如:Dist(2,4), Dist(6,1)
2) node1 和 node2 没有直接或间接的父子关系。
例如,Dist(4,3), 他们需要一个共同的祖先节点1 连接起来
Dist(n1, n2) = Dist(root, n1) + Dist(root, n2) - 2*Dist(root, lca)
*/
#include<iostream>
using namespace std;
struct Node{
int data;
Node *lchild;
Node *rchild;
};
int max(int a,int b)
{
return a>b?a:b;
}
Node *getPublicParetnNode(Node *root,int n1,int n2)
{
if(root==NULL) return NULL;
if(root->data==n1||root->data==n2)
return root;
Node *lNode=getPublicParetnNode(root->lchild,n1,n2);
Node *rNode=getPublicParetnNode(root->rchild,n1,n2);
if(!lNode&&!rNode) return NULL;
else if(lNode&&rNode) return root;
else return lNode==NULL?rNode:lNode;
}
int getDistanceToRoot(Node *root,int n)
{
if(root==NULL)return -1;
if(root->data==n) return 0;
int level=getDistanceToRoot(root->lchild,n);
if(level==-1)//表示左子树上没有。
level=getDistanceToRoot(root->rchild,n);
if(level!=-1)
return level+1;
return -1;
}
void buildTree(Node *&root)
{
int num;
scanf("%d",&num);
if(num==0)
{
root=NULL;
return;
}
root=new Node;
root->data=num;
buildTree(root->lchild);
buildTree(root->rchild);
}
int getTwoNodeDis(Node *root,int n1,int n2)
{
int d1=getDistanceToRoot(root,n1);
int d2=getDistanceToRoot(root,n2);
Node *node=getPublicParetnNode(root,n1,n2);
int d3=getDistanceToRoot(root,node);
return d1+d2-2*d3;
}