您的位置:首页 > 职场人生

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

2016-12-29 20:29 337 查看
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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息