标签:
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Tree Depth-first Search
1.采用递归的方法来做
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode
{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//用递归的方法来做(有点类似于动态规划的感觉)
int max(int a,int b);
int maxDepth(TreeNode *root) 
{
	int left,right;
	if(root==NULL)
		return 0;
	left=maxDepth(root->left);//左子树的深度
	right=maxDepth(root->right);//右子树的深度
	return 1+max(left,right);//选取其中深度大的那个,再加上本身的一,为本身这个结点深度
}
int max(int a,int b)
{
	if(a>=b)
		return a;
	else
		return b;
}
int main(int argc,char** argv)
{
}
2.采用队列的方式来做
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct TreeNode
{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//采用队列的方式来做,采用队列的方式一层一层的对二叉树进行遍历,并记录层数
int maxDepth(TreeNode *root)
{
	if(root==NULL)
		return 0;
	int deep=0;//深度
	int row_size=1;//每一层的元素个数(第一层只有一个根节点)
	queue<TreeNode*> temp;//算法所用的队列.
	temp.push(root);
	while(!temp.empty())//直到队列为空才停止
	{
		TreeNode* temp_node;
		while(row_size--)//依次的遍历每一层,将下一层的每一个元素都进队列,并将上一层
		{//的队列都出列。
			temp_node=temp.front();
			if(temp_node->left!=NULL)
				temp.push(temp_node->left);
			if(temp_node->right!=NULL)
				temp.push(temp_node->right);
			temp.pop();
		}
		row_size=temp.size();//记录下这一层的元素有多少个
		deep+=1;//记录深度
	}
	return deep;
}
int main(int argc,char** argv)
{
}
leetcode——Maximum Depth of Binary Tree (递归,)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4425054.html