二叉树任意两点间最短路径(利用栈-找公共祖先,不需要建立二叉树)

在这里插入图片描述
在这里插入图片描述

代码:

#include<bits/stdc++.h>
using namespace std;

int main()
{
    
    
	int T;
	cin>>T;
	while(T--)
	{
    
    
		int n,m;
		cin>>n>>m;
		int a[2011]={
    
    0};
		a[1]=1000;//父节点 
		for(int i=1;i<=n;++i)
		{
    
    
			int lchild,rchild;
			cin>>lchild>>rchild;
			if(lchild!=-1) a[lchild]=i;//记录祖先 
			if(rchild!=-1) a[rchild]=i;
		}
		
		stack<int>st1,st2;	
		while(m--)
		{
    
    
			while(!st1.empty()) st1.pop();
			while(!st2.empty()) st2.pop();
			int x,y;
			cin>>x>>y;
			
			
			st1.push(x);			
			while(a[x]!=1000)//要查询的节点及其祖先进栈
			{
    
    
				x=a[x];
				st1.push(x);
			}
			
			
			st2.push(y);			
			while(a[y]!=1000)
			{
    
    
				y=a[y];
				st2.push(y);
			}
			
			
			while(!st1.empty()&&!st2.empty())
			{
    
    
				if(st1.top()==st2.top())//找到公共祖先节点 
				{
    
    
					st1.pop();
					st2.pop();
				}
				else
				{
    
    
					break;
				}
			}
			
			
			cout<<st1.size()+st2.size()<<endl;//各栈剩余的节点组成路径
		}
		
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43901182/article/details/113002415
今日推荐