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
- [LeetCode]104.Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 【LeetCode】104.Maximum Depth of Binary Tree
- [Leetcode] 104. Maximum Depth of Binary Tree
- LeetCode --- 104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- leetCode 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree LeetCode
- 104. Maximum Depth of Binary Tree LeetCode
- 104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- leetcode:104. Maximum Depth of Binary Tree
- 排序
- 二级下拉菜单的使用
- java中使用WebView提取指定网页的HTML内容
- July 14th 模拟赛C T3 灌水 Solution
- 十进制,二进制的转换
- 104. Maximum Depth of Binary Tree
- 接口的幂等性
- 求树的重心
- 《老人与海》后感
- “荒谬”的等式:1+2+3+4+…+∞= -1/12;1^2+2^2+3^2+4^2+…+∞^2=0
- HTML5中应该记住的知识
- <第一行代码>笔记一
- Java的方法重写规则
- Hdu 3812 Sea Sky (模拟_搜索)