二叉树的相关面试题<二>

1.求二叉树中最远的两个节点的

 思路:解这个题的思路是用递归求解,定义一个变量distance,后序遍历,从叶子节点开始判断。对于当前节点,求他的左右子树的高度和 和distance比较,如果高度和大,把他保存到变量distance中,否则distance不变 

如图:


int GetFarthestDistance()
	{
		assert(_root);
		int distance=0;  //记录最远的距离
		return _GetFarthestDistance(_root,distance);
	}

int _GetFarthestDistance(Node* root,int& distance)
	{
		if(root==NULL)
			return 0;
		//后序遍历
		int left=_GetFarthestDistance(root->_left ,distance);
		int right=_GetFarthestDistance(root->_right ,distance);
		if(left+right>distance)  //更新distance
			distance=left+right;
		return left>right?left+1:right+1;
	}

2.求两个节点最近的公共祖先


Node* GetRecentlyAncestor(int root1,int root2)
	{
		stack<Node*> v1;  //保存到root1路径
		stack<Node*> v2;  //保存到root2路径

		int flag=0;       //判断有没有找到
		_GetRecentlyAncestor(_root,root1,v1,flag);
		flag=0;
		_GetRecentlyAncestor(_root,root2,v2,flag);
		Node* top1=v1.top ();
		Node* top2=v2.top ();
		Node* prev=top1;
		//最近的公共祖先就是在路径中第一不相等的数的前一个
		while((!v1.empty())&&(!v2.empty()))
		{
			if(top1==top2)
			{
				prev=top1;
				v1.pop();
				if(!v1.empty ())
				    top1=v1.top();
				v2.pop();
				if(!v2.empty ())
					top2=v2.top();		
			}
			else
			{
				return prev;
			}
		}
		if(v1.empty()||v2.empty ())
		{
			return prev;
		}
	}

void _GetRecentlyAncestor(Node* root,int rootData,stack<Node*>& v,int& flag)
	{
		if(root==NULL||flag==1)//||flag==1是为了表示找到的节点在最子树,不用去访问右子树了
			return;

		//后序遍历
		_GetRecentlyAncestor(root->_left ,rootData,v,flag);
		_GetRecentlyAncestor(root->_right,rootData,v,flag);
		//当前节点
		if(root->_data ==rootData||flag==1) //||flag==1是为了表示找到的节点再当前的子树中
		{
			v.push(root);
			flag=1;
		}

	}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值