class Tree {
public:
int INF=1e9+7;
TreeNode *LCA(TreeNode* root,int p,int q)//find the common ancestor of p and q
{
if(!root)
return root;
TreeNode *left=LCA(root->left,p,q);
TreeNode *right=LCA(root->right,p,q);
if(root->val==p||root->val==q)
return root;//find one
else if(left&&right)
return root;
return left?left:right;
}
int distanceToRoot(TreeNode *root,int x)//the distance from root to the node
{
if(!root)
return INF;
if(root->val==x)
return 0;
return 1+min(distanceToRoot(root->left,x),distanceToRoot(root->right,x));
}
int distanceInTree(TreeNode* root, int p, int q)
{
TreeNode *pqLca=LCA(root,p,q);
int distance1=distanceToRoot(pqLca,p);
int distance2=distanceToRoot(pqLca,q);
return distance1+distance2;
}
};
代码收集0016——树
最新推荐文章于 2023-08-06 21:54:15 发布