104. Maximum Depth of Binary Tree

leetcode 104

Question: 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.


有两种解题思路,一种采用深度遍历DFS,利用递归的方法,一种采用广度遍历(层次遍历),利用队列。

#include<iostream>
#include<queue>
#include<malloc.h>
using namespace std;

//树
typedef struct TreeNode {
    int val;
	TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
	TreeNode(): left(NULL),right(NULL) {}
}*BiTree;

/*
//DFS-递归
class Solution {
public:
    int maxDepth(TreeNode* root) {
		if(root==NULL)
			return 0;
		int l=maxDepth(root->left);
		int r=maxDepth(root->right);
		return (l<r)?r+1:l+1;
    }
};
*/

//BFS-队列
class Solution {
public:
    //二叉树最大深度(层次遍历,遍历一层高度加1)
    int maxDepth(TreeNode *root) {
		if(root==NULL)
			return 0;
		int nCount=1;//保存当前层次节点个数
		int nDepth=0;
		queue<TreeNode *> queue;	
		queue.push(root);
		while(!queue.empty())
		{
			TreeNode *node=queue.front();
			queue.pop();
			nCount--;
			if(node->left)
				queue.push(node->left);
			if(node->right)
				queue.push(node->right);
			if(nCount==0)
			{
				nDepth++;
				nCount=queue.size();
			}
		}
		return nDepth;
    }
	//构造二叉树
	//root必须是指针类型,因为函数内需要新创建
	//不能是:参数TreeNode *root及main函数中为TreeNode *root;S.CreateBiTree(root);这样在创建完成后不能传回,即这里函数参数为值传递
	void CreateBiTree(BiTree &root)
	{
		char data;
		//按先序输入二叉树,-1表示空树
		data=getchar();
		if(data=='#')
			root=NULL;
		else
		{
			root=new TreeNode();
			root->val=data;
			CreateBiTree(root->left);
			CreateBiTree(root->right);
		}
		return;
	}
};

void main()
{
	Solution S;
	BiTree root=NULL;
	S.CreateBiTree(root);
	cout<<root->val<<endl;
	cout<<S.maxDepth(root)<<endl;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值