1. 程式人生 > >二叉樹的幾道典型例題

二叉樹的幾道典型例題

1.求二叉樹的高度

int _GetTreeHight(Node<T>* pRoot)
	{
		if(pRoot==NULL)
			return 0;

		if(pRoot->_pLeft==NULL&&pRoot->_pRight==NULL)
			return 1;

		int left=_GetTreeHight(pRoot->_pLeft)+1;
		int right=_GetTreeHight(pRoot->_pRight)+1;

		return left>right?left:right;
	}
2.求葉子結點的個數
	int _LeafNodeNum(Node<T>* pRoot)
	{
		if(pRoot==NULL)
			return 0;

		if(pRoot->_pLeft==NULL&&pRoot->_pRight==NULL)
			return 1;

		int left=_LeafNodeNum(pRoot->_pLeft);
		int right=_LeafNodeNum(pRoot->_pRight);

		return left+right;
	}
3.判斷一個數據是否在一棵二叉樹中
Node<T>* _Find(Node<T>* pRoot,const T& data)
	{
		if(pRoot==NULL)
			return NULL;

		if(pRoot->_value==data)
			return pRoot;

		Node<T>* pcur=_Find(pRoot->_pLeft,data);
		if(pcur)
			return pcur;

		return _Find(pRoot->_pRight,data);
	}

4.求二叉樹中兩個結點的最近公共祖先結點
	bool GetWay(Node<T>* pRoot,Node<T>* N,vector<Node<T>*>& v,size_t index)
	{
		if(pRoot==NULL)
			return false;

		v.push_back(pRoot);
		if(pRoot==N)
			return true;

		pRoot=v.back();
		if(GetWay(pRoot->_pLeft,N,v,index+1))
			return true;

		v.pop_back();
		pRoot=v.back();
		return GetWay(pRoot->_pRight,N,v,index+1);
	}

	Node<T>* _LastAncestorNode(Node<T>* pRoot,Node<T>* N1,Node<T>* N2)
	{
		if(pRoot==NULL||(pRoot->_pLeft==NULL&&pRoot->_pRight==NULL))
			return NULL;

		vector<Node<T>*> v1;
		vector<Node<T>*> v2;
		if(GetWay(pRoot,N1,v1,0)&&GetWay(pRoot,N2,v2,0))
		{
			for(size_t i=v1.size();i>0;--i)
			{
				for(size_t j=v2.size();j>0;--j)
				{
					if(v1[i-1]==v2[j-1])
						return v1[i-1];
				}
			}
		}
		
		return NULL;
	}
5.查詢一個節點的雙親節點
	Node<T>* _FindParent(Node<T>* pRoot,Node<T>* pRet)
	{
		if(pRoot==NULL||pRet==pRoot)
			return NULL;

		if(pRoot->_pLeft==pRet||pRoot->_pRight==pRet)
		{
			return pRoot;
		}
		
		Node<T>* pcur=_FindParent(pRoot->_pLeft,pRet);
		if(pcur)
			return pcur;

		return _FindParent(pRoot->_pRight,pRet);

	}

6.求二叉樹中最遠的兩個結點之間的距離
	int _DistanceOfNodes(Node<T>* pRoot)
	{
		if(pRoot==NULL)
			return 0;

		int left=_GetTreeHight(pRoot->_pLeft);
		int right=_GetTreeHight(pRoot->_pRight);

		return left+right;
	}

7.判斷一棵二叉樹是否是完全二叉樹
	bool _IsCompleteBinaryTree(Node<T>* pRoot)
	{
		if(pRoot==NULL)
			return false;

		queue<Node<T>*> q;
		q.push(pRoot);

		while((pRoot=q.front())!=NULL)
		{
			q.push(pRoot->_pLeft);
			q.push(pRoot->_pRight);
			q.pop();
		}

		while(!q.empty()&&(pRoot=q.front())==NULL)
		{
			q.pop();	
		}

		if(!q.empty())
			return false;

		return true;

	}

8.求二叉樹的映象
	BinaryTree<T> ImageBinaryTree()
	{
		BinaryTree<T> bt;
		bt._pRoot=CopyTree(_pRoot);
		_ImageBinaryTree(bt._pRoot);
		return bt;
	}
	
        void _ImageBinaryTree(Node<T>* pRoot)
	{
		Node<T>* pcur=pRoot;

		if(pcur==NULL||(pcur->_pLeft==NULL&&pcur->_pRight==NULL))
			return ;

		swap(pcur->_pLeft,pcur->_pRight);

		_ImageBinaryTree(pcur->_pLeft);
		_ImageBinaryTree(pcur->_pRight);
	}