104. Maximum Depth of Binary Tree

来源:互联网 发布:define js 模块 编辑:程序博客网 时间:2024/06/01 17:04

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
原创粉丝点击