二叉树面试题总结

http://www.cnblogs.com/10jschen/archive/2012/08/29/2662942.html

轻松搞定面试中的二叉树题目
class BinaryTree;
class Node
{
public:
	Node(){lchild=NULL;rchild=NULL;}
    Node(int data,Node* left=NULL,Node* right=NULL)
	{
		info=data;
		lchild=left;
		rchild=right;
	}
private:
	Node* lchild,*rchild;
	int info;
	friend class BinaryTree;
};
class BinaryTree
{
public:
	BinaryTree(){root=NULL;}
	~BinaryTree(){Destory(root);}
	void Creat(int *data,int n);
	void InOrder(){InOrder(root);}
    void PreOder(){PreOder(root);}
	void PostOrder(){PostOrder(root);}
	void LevelTraverse(){LevelTraverse(root);}
	int  GetNodeNum(){return GetNodeNum(root);}
	int  GetDepth(){return GetDepth(root);}
private:
	Node* root;
	void InOrder(Node* Current);
	void PreOder(Node* Current);
	void PostOrder(Node* Current);
	void Insert(const int &data,Node* &b);
	void Destory(Node* Current);
	int  GetNodeNum(Node* Current);
	int  GetDepth(Node* Current);	
	void LevelTraverse(Node* Current);
};
void BinaryTree::Insert(const int &data,Node* &b)
{
	if (b==NULL)
	{
		b=new Node(data);
	}
	else if (data<b->info)
	{
		Insert(data,b->lchild);
	} 
	else
	{
       Insert(data,b->rchild);
	}
}
void BinaryTree::Creat(int *data,int n)
{
	for (int i=0;i<n;i++)
	{
		Insert(data[i],root);
	}
}
void BinaryTree::Destory(Node* Current)
{
   if (Current!=NULL)
   {
	   Destory(Current->lchild);
	   Destory(Current->rchild);
	   delete Current;
   }
}
void BinaryTree::InOrder(Node* Current)//中序遍历
{
	if (Current!=NULL)
	{
		InOrder(Current->lchild);
		cout<<Current->info<<'\t';
		InOrder(Current->rchild);
	}
}
void BinaryTree::PreOder(Node* Current)//前序遍历
{
	if (Current!=NULL)
	{
		cout<<Current->info<<'\t';
		InOrder(Current->lchild);
		InOrder(Current->rchild);
	}
}
void BinaryTree::PostOrder(Node* Current)//后序遍历
{
	if (Current!=NULL)
	{
		InOrder(Current->lchild);
		InOrder(Current->rchild);
		cout<<Current->info<<'\t';
	}
}
//1. 求二叉树中的节点个数
//递归解法:
//(1)如果二叉树为空,节点个数为0
//(2)如果二叉树不为空,二叉树节点个数 = 左子树节点个数 + 右子树节点个数 + 1
int BinaryTree::GetNodeNum(Node* Current) //结点个数
{  
	if(Current == NULL) // 递归出口  
		return 0;  
	return GetNodeNum(Current->lchild) + GetNodeNum(Current->rchild) + 1;  
}  
//2. 求二叉树的深度
//递归解法:
//(1)如果二叉树为空,二叉树的深度为0
//(2)如果二叉树不为空,二叉树的深度 = max(左子树深度, 右子树深度) + 1
int BinaryTree::GetDepth(Node* Current)  
{  
	if(Current == NULL) // 递归出口  
		return 0;  
	int depthLeft = GetDepth(Current->lchild)+1;  
	int depthRight = GetDepth(Current->rchild)+1;  
	 return depthLeft > depthRight ? (depthLeft ) : (depthRight);
}  
//4.分层遍历二叉树(按层次从上往下,从左往右)
//相当于广度优先搜索,使用队列实现。队列初始化,将根节点压入队列。当队列不为空,进行如下操作:弹出一个节点,访问,
//若左子节点或右子节点不为空,将其压入队列。
void BinaryTree::LevelTraverse(Node* Current)  
{  
	if(Current == NULL)  
		return;  
	queue<Node*> q;  
	q.push(Current);  
	while(!q.empty())  
	{  
		Node * pNode = q.front();  
		q.pop();  
		cout<<pNode->info<<'\t';; // 访问节点  
		if(pNode->lchild != NULL)  
			q.push(pNode->lchild);  
		if(pNode->rchild != NULL)  
			q.push(pNode->rchild);  
	}  
	return;  
}  
5.二叉搜索树转换为有序双向链表
http://blog.csdn.net/ljianhui/article/details/22338405
http://www.cnblogs.com/10jschen/archive/2012/08/29/2662942.html
/****************************************************************************** 
参数: 
pRoot: 二叉查找树根节点指针 
pFirstNode: 转换后双向有序链表的第一个节点指针 
pLastNode: 转换后双向有序链表的最后一个节点指针 
******************************************************************************/  
void Convert(BinaryTreeNode * pRoot,   
             BinaryTreeNode * & pFirstNode, BinaryTreeNode * & pLastNode)  
{  
    BinaryTreeNode *pFirstLeft, *pLastLeft, * pFirstRight, *pLastRight;  
    if(pRoot == NULL)   
    {  
        pFirstNode = NULL;  
        pLastNode = NULL;  
        return;  
    }  
  
    if(pRoot->m_pLeft == NULL)  
    {  
        // 如果左子树为空,对应双向有序链表的第一个节点是根节点  
        pFirstNode = pRoot;  
    }  
    else  
    {  
        Convert(pRoot->m_pLeft, pFirstLeft, pLastLeft);  
        // 二叉查找树对应双向有序链表的第一个节点就是左子树转换后双向有序链表的第一个节点  
        pFirstNode = pFirstLeft;  
        // 将根节点和左子树转换后的双向有序链表的最后一个节点连接  
        pRoot->m_pLeft = pLastLeft;  
        pLastLeft->m_pRight = pRoot;  
    }  
  
    if(pRoot->m_pRight == NULL)  
    {  
        // 对应双向有序链表的最后一个节点是根节点  
        pLastNode = pRoot;  
    }  
    else  
    {  
        Convert(pRoot->m_pRight, pFirstRight, pLastRight);  
        // 对应双向有序链表的最后一个节点就是右子树转换后双向有序链表的最后一个节点  
        pLastNode = pLastRight;  
        // 将根节点和右子树转换后的双向有序链表的第一个节点连接  
        pRoot->m_pRight = pFirstRight;  
        pFirstRight->m_pRight = pRoot;  
    }  
  
    return;  
}  
 6. 求二叉树第K层的节点个数
递归解法:
(1)如果二叉树为空或者k<1返回0
(2)如果二叉树不为空并且k==1,返回1
(3)如果二叉树不为空且k>1,返回左子树中k-1层的节点个数与右子树k-1层节点个数之和
参考代码如下:
int GetNodeNumKthLevel(BinaryTreeNode * pRoot, int k)  
{  
    if(pRoot == NULL || k < 1)  
        return 0;  
    if(k == 1)  
        return 1;  
    int numLeft = GetNodeNumKthLevel(pRoot->m_pLeft, k-1); // 左子树中k-1层的节点个数  
    int numRight = GetNodeNumKthLevel(pRoot->m_pRight, k-1); // 右子树中k-1层的节点个数  
    return (numLeft + numRight);  
} 
7.树的子结构 
http://blog.csdn.net/htyurencaotang/article/details/9398929
1.	struct BinaryTreeNode  
2.	{  
3.	    int m_nValue;  
4.	    BinaryTreeNode *m_pLeft;  
5.	    BinaryTreeNode *m_pRight;  
6.	};  
7.	  
8.	bool DoesTree1haveTree2(BinaryTreeNode *pRoot1, BinaryTreeNode *pRoot2)  
9.	{  
10.	    if (pRoot2 == NULL)  
11.	    {  
12.	        return true;  
13.	    }  
14.	  
15.	    if (pRoot1 == NULL)  
16.	    {  
17.	        return false;  
18.	    }  
19.	  
20.	    if (pRoot1->m_nValue != pRoot2->m_nValue)  
21.	    {  
22.	        return false;  
23.	    }  
24.	  
25.	    return DoesTree1haveTree2(pRoot1->m_pLeft, pRoot2->m_pLeft)  
26.	        && DoesTree1haveTree2(pRoot1->m_pRight, pRoot2->m_pRight);  
27.	}  
28.	  
29.	//判断B是否为A的子结构  
30.	bool IsSubStruct(BinaryTreeNode *pRootOfTreeA, BinaryTreeNode *pRootOfTreeB)  
31.	{  
32.	   bool result = false;  
33.	   if (pRootOfTreeA != NULL && pRootOfTreeB != NULL)  
34.	   {  
35.	       if (pRootOfTreeA->m_nValue == pRootOfTreeB->m_nValue)  
36.	       {  
37.	           result = DoesTree1haveTree2(pRootOfTreeA, pRootOfTreeB);  
38.	       }  
39.	  
40.	       if (!result)  
41.	       {  
42.	           result = IsSubStruct(pRootOfTreeA->m_pLeft, pRootOfTreeB);  
43.	       }  
44.	  
45.	       if (!result)  
46.	       {  
47.	           result = IsSubStruct(pRootOfTreeA->m_pRight, pRootOfTreeB);  
48.	       }  
49.	   }   
50.	  
51.	   return result;  
52.	}  

8.如果为二叉搜索树中找出两节点的最近祖先节点

有简单的方法,详见:

http://hi.baidu.com/yibobin/blog/item/45b5721b5811170c8618bf9b.html

检查当前节点;如果value1和value2都小于当前节点的值,检查它的左子节点;如果value1和value2都大于当前节点的值,检查它的右子节点;否则,当前节点就是最近共同祖先。
Node* findLowerstCommonAncestor(Node* root, int value1, int value2)
{
    while ( root != NULL )
    {
        int value = root->getValue();
        if ( value > value1 && value > value2 )
            root = root->getLeft();
        else if (value < value1 && value < value2)
            root = root->getRight();
        else
            return root;
    }
    return NULL;
}
9.普通二叉树
先求从根节点到两个节点的路径,然后再比较对应路径的节点就行,最后一个相同的节点也就是他们在二叉树中的最低公共祖先节点
参考代码如下:
1.	bool GetNodePath(BinaryTreeNode * pRoot, BinaryTreeNode * pNode,   
2.	                 list<BinaryTreeNode *> & path)  
3.	{  
4.	    if(pRoot == pNode)  
5.	        return true;  
6.	    if(pRoot == NULL)  
7.	        return false;  
8.	    path.push_back(pRoot);  
9.	    bool found = false;  
10.	    found = GetNodePath(pRoot->m_pLeft, pNode, path);  
11.	    if(!found)  
12.	        found = GetNodePath(pRoot->m_pRight, pNode, path);  
13.	    if(!found)  
14.	        path.pop_back();  
15.	    return found;  
16.	}  
17.	BinaryTreeNode * GetLastCommonParent(BinaryTreeNode * pRoot,   
18.	                                     BinaryTreeNode * pNode1,   
19.	                                     BinaryTreeNode * pNode2)  
20.	{  
21.	    if(pRoot == NULL || pNode1 == NULL || pNode2 == NULL)  
22.	        return NULL;  
23.	  
24.	    list<BinaryTreeNode*> path1;  
25.	    GetNodePath(pRoot, pNode1, path1);  
26.	    list<BinaryTreeNode*> path2;  
27.	    GetNodePath(pRoot, pNode2, path2);  
28.	  
29.	    BinaryTreeNode * pLast = NULL;  
30.	    list<BinaryTreeNode*>::const_iterator iter1 = path1.begin();  
31.	    list<BinaryTreeNode*>::const_iterator iter2 = path2.begin();  
32.	    while(iter1 != path1.end() && iter2 != path2.end())  
33.	    {  
34.	        if(*iter1 == *iter2)  
35.	            pLast = *iter1;  
36.	        else  
37.	            break;  
38.	        iter1++;  
39.	        iter2++;  
40.	    }  
41.	  
42.	    return pLast;  
43.	}  
12. 求二叉树中节点的最大距离
http://blog.163.com/shi_shun/blog/static/2370784920109264337177/
即二叉树中相距最远的两个节点之间的距离。
递归解法:
(1)如果二叉树为空,返回0,同时记录左子树和右子树的深度,都为0
(2)如果二叉树不为空,最大距离要么是左子树中的最大距离,要么是右子树中的最大距离,要么是左子树节点中到根节点的最大距离+右子树节点中到根节点的最大距离,同时记录左子树和右子树节点中到根节点的最大距离。
参考代码如下:
int GetMaxDistance(BinaryTreeNode * pRoot, int & maxLeft, int & maxRight)  
{  
    // maxLeft, 左子树中的节点距离根节点的最远距离  
    // maxRight, 右子树中的节点距离根节点的最远距离  
    if(pRoot == NULL)  
    {  
        maxLeft = 0;  
        maxRight = 0;  
        return 0;  
    }  
    int maxLL, maxLR, maxRL, maxRR;  
    int maxDistLeft, maxDistRight;  
    if(pRoot->m_pLeft != NULL)  
    {  
        maxDistLeft = GetMaxDistance(pRoot->m_pLeft, maxLL, maxLR);  
        maxLeft = max(maxLL, maxLR) + 1;  
    }  
    else  
    {  
        maxDistLeft = 0;  
        maxLeft = 0;  
    }  
    if(pRoot->m_pRight != NULL)  
    {  
        maxDistRight = GetMaxDistance(pRoot->m_pRight, maxRL, maxRR);  
        maxRight = max(maxRL, maxRR) + 1;  
    }  
    else  
    {  
        maxDistRight = 0;  
        maxRight = 0;  
    }  
    return max(max(maxDistLeft, maxDistRight), maxLeft+maxRight);  
} 
13. 由前序遍历序列和中序遍历序列重建二叉树
二叉树前序遍历序列中,第一个元素总是树的根节点的值。中序遍历序列中,左子树的节点的值位于根节点的值的左边,右子树的节点的值位于根节点的值的右边。
递归解法:
(1)如果前序遍历为空或中序遍历为空或节点个数小于等于0,返回NULL。
(2)创建根节点。前序遍历的第一个数据就是根节点的数据,在中序遍历中找到根节点的位置,可分别得知左子树和右子树的前序和中序遍历序列,重建左右子树。
1.	BinaryTreeNode * RebuildBinaryTree(int* pPreOrder, int* pInOrder, int nodeNum)  
2.	{  
3.	    if(pPreOrder == NULL || pInOrder == NULL || nodeNum <= 0)  
4.	        return NULL;  
5.	    BinaryTreeNode * pRoot = new BinaryTreeNode;  
6.	    // 前序遍历的第一个数据就是根节点数据  
7.	    pRoot->m_nValue = pPreOrder[0];  
8.	    pRoot->m_pLeft = NULL;  
9.	    pRoot->m_pRight = NULL;  
10.	    // 查找根节点在中序遍历中的位置,中序遍历中,根节点左边为左子树,右边为右子树  
11.	    int rootPositionInOrder = -1;  
12.	    for(int i = 0; i < nodeNum; i++)  
13.	        if(pInOrder[i] == pRoot->m_nValue)  
14.	        {  
15.	            rootPositionInOrder = i;  
16.	            break;  
17.	        }  
18.	    if(rootPositionInOrder == -1)  
19.	    {  
20.	        throw std::exception("Invalid input.");  
21.	    }  
22.	    // 重建左子树  
23.	    int nodeNumLeft = rootPositionInOrder;  
24.	    int * pPreOrderLeft = pPreOrder + 1;  
25.	    int * pInOrderLeft = pInOrder;  
26.	    pRoot->m_pLeft = RebuildBinaryTree(pPreOrderLeft, pInOrderLeft, nodeNumLeft);  
27.	    // 重建右子树  
28.	    int nodeNumRight = nodeNum - nodeNumLeft - 1;  
29.	    int * pPreOrderRight = pPreOrder + 1 + nodeNumLeft;  
30.	    int * pInOrderRight = pInOrder + nodeNumLeft + 1;  
31.	    pRoot->m_pRight = RebuildBinaryTree(pPreOrderRight, pInOrderRight, nodeNumRight);  
32.	    return pRoot;  
33.	}  
同样,有中序遍历序列和后序遍历序列,类似的方法可重建二叉树,但前序遍历序列和后序遍历序列不同恢复一棵二叉树,证明略。
14.判断二叉树是不是完全二叉树
若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中     在最左边,这就是完全二叉树。
有如下算法,按层次(从上到下,从左到右)遍历二叉树,当遇到一个节点的左子树为空时,则该节点右子树必须为空,且后面遍历的节点左右子树都必须为空,否则不是完全二叉树。
1.	bool IsCompleteBinaryTree(BinaryTreeNode * pRoot)  
2.	{  
3.	    if(pRoot == NULL)  
4.	        return false;  
5.	    queue<BinaryTreeNode *> q;  
6.	    q.push(pRoot);  
7.	    bool mustHaveNoChild = false;  
8.	    bool result = true;  
9.	    while(!q.empty())  
10.	    {  
11.	        BinaryTreeNode * pNode = q.front();  
12.	        q.pop();  
13.	        if(mustHaveNoChild) // 已经出现了有空子树的节点了,后面出现的必须为叶节点(左右子树都为空)  
14.	        {  
15.	            if(pNode->m_pLeft != NULL || pNode->m_pRight != NULL)  
16.	            {  
17.	                result = false;  
18.	                break;  
19.	            }  
20.	        }  
21.	        else  
22.	        {  
23.	            if(pNode->m_pLeft != NULL && pNode->m_pRight != NULL)  
24.	            {  
25.	                q.push(pNode->m_pLeft);  
26.	                q.push(pNode->m_pRight);  
27.	            }  
28.	            else if(pNode->m_pLeft != NULL && pNode->m_pRight == NULL)  
29.	            {  
30.	                mustHaveNoChild = true;  
31.	                q.push(pNode->m_pLeft);  
32.	            }  
33.	            else if(pNode->m_pLeft == NULL && pNode->m_pRight != NULL)  
34.	            {  
35.	                result = false;  
36.	                break;  
37.	            }  
38.	        }  
39.	    }  
40.	    return result;  
41.	}  

15. 二叉树非递归遍历http://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html
void BinaryTree::LastOrder(Node* Current)//非递归的后序遍历
{
	 stack<Node*>vis;
	 stack<int>vistime;
     Node* q=Current;
	 while(q!=NULL||!vis.empty())
	 {
		 while(q!=NULL)
		 {
			 vis.push(q);
			 vistime.push(1);
			 q=q->lchild;
		 }
		 if(!vis.empty())
		 {
              if (vistime.top()==1)
              {
				  vistime.top()=2;
                   q=vis.top();
				  q=q->rchild;
              } 
              else
              {
                  q=vis.top();
				  vis.pop();
				  vistime.pop();
                  cout<<q->info<<"\t";
				  q=NULL;
              }
		 }
	 }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值