博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

程序员面试100题之二十七,二元树的深度

Posted on 2010-09-24 16:56  KurtWang  阅读(220)  评论(0)    收藏  举报
// 100_27.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

struct Node
{
	Node * left;
	Node * right;
	int value;
};

int depth(Node * root)
{
	if(!root)
		return 0;
	int left = 0;
	int right = 0;
	if(root->left)
		left = depth(root->left);
	if(root->right)
		right = depth(root->right);

	return left>right?left+1:right+1;
}

int _tmain(int argc, _TCHAR* argv[])
{
	Node * n1 = new Node();
	Node * n2 = new Node();
	Node * n3 = new Node();
	
	n1->left = n2;
	n1->right = n3;
	n1->value = 1;

	n2->left = NULL;
	n2->right = NULL;
	n2->value = 2;

	n3->left = NULL;
	n3->right = NULL;
	n3->value = 3;
	
	printf("%d\n", depth(n1));
	return 0;
}