每日一练(39) - 二叉树的深度

题目来自剑指Offer

题目:求二叉树的深度

代码

#include <iostream>
#include <assert.h>
using namespace std;

const int SIZE = 100;

struct BinaryTreeNode 
{
	char m_nValue;
	BinaryTreeNode* m_pLeft;
	BinaryTreeNode* m_pRight;
};

int Depth(BinaryTreeNode* pRoot)
{
	if (!pRoot)
	{
		return 0;
	}
	int nLeftDepth = Depth(pRoot->m_pLeft);
	int nRightDepth = Depth(pRoot->m_pRight);
	return max(nLeftDepth,nRightDepth) + 1;
}

void Create(BinaryTreeNode*& pRoot)    
{    
	char newData;    
	cin >> newData;    
	if ('#' == newData)    
	{    
		pRoot = NULL;    
	}    
	else    
	{    
		pRoot = new BinaryTreeNode;    
		pRoot->m_nValue = newData;    
		Create(pRoot->m_pLeft);    
		Create(pRoot->m_pRight);     
	}    
}    

int main()
{
	BinaryTreeNode* Root = NULL;
	Create(Root);
	cout<<"Depth: "<<Depth(Root)<<endl;
	system("pause");
	return 1;
}
注意:

树的构建类似树的子结构,这里不再详述。

你可能感兴趣的:(每日一练(39) - 二叉树的深度)