Maximum Depth of Binary Tree(leetcode)
来源:互联网 发布:网络协议分析考试 编辑:程序博客网 时间:2024/05/18 03:36
题目:
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.
题目来源:https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/
解题思路:1、广搜2、深搜,找出最大值
广搜代码:
#include<iostream>#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){int result=0;if(root==NULL)return result;queue<TreeNode *> q;q.push(root);int k=0,level=1;while(!q.empty()){k=level;level=0;for(int i=0;i<k;i++){if(q.front()->left!=NULL){q.push(q.front()->left);level++;}if(q.front()->right!=NULL){q.push(q.front()->right);level++;}q.pop();}result++;}return result;}int main(){TreeNode* root=new TreeNode(1);root->left=new TreeNode(2);root->right=new TreeNode(3);root->left->left=new TreeNode(4);root->right->left=new TreeNode(5);int results=maxDepth(root);system("pause");return 0;}
深搜代码:
#include<iostream>#include<stack>using namespace std;struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};void dfs(TreeNode *root,int result,int &max){if(root==NULL){if(result>max)max=result;return ;}++result;dfs(root->left,result,max);dfs(root->right,result,max);}int maxDepth(TreeNode *root){int max=0;if(root==NULL)return max;int result=0;dfs(root,result,max);return max;}int main(){TreeNode* root=new TreeNode(1);root->left=new TreeNode(2);root->right=new TreeNode(3);root->left->left=new TreeNode(4);root->right->left=new TreeNode(5);int results=maxDepth(root);system("pause");return 0;}利用栈进行迭代的算法以后再写。
0 0
- Leetcode - Tree - Maximum Depth of Binary Tree
- [leetcode][tree] Maximum Depth of Binary Tree
- LeetCode Maximum Depth of Binary Tree
- [Leetcode] Maximum Depth of Binary Tree
- leetcode 24: Maximum Depth of Binary Tree
- [LeetCode] Maximum Depth of Binary Tree
- Leetcode 104 Maximum Depth of Binary Tree
- 【leetcode】Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- [LeetCode]Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- Leetcode: Maximum Depth of Binary Tree
- LeetCode-Maximum Depth of Binary Tree
- [leetcode] Maximum Depth of Binary Tree
- LeetCode - Maximum Depth of Binary Tree
- LeetCode:Maximum Depth of Binary Tree
- LeetCode | Maximum Depth of Binary Tree
- 【leetcode】Maximum Depth of Binary Tree
- asd'sa'da's
- IOS 监控屏幕旋转
- 第11周项目2-求最大公约数
- Gson解析boolean值的注意
- 《Linux设备驱动程序》——并发和竞态
- Maximum Depth of Binary Tree(leetcode)
- webService详解(一)
- C#实验10一二三四合集
- 印度易瑞沙 复员军人守护3小时救被撞老人
- Android DiskLruCache完全解析,硬盘缓存的最佳方案
- 特罗凯 北漂男子收废品为生兼职为行人义务指路
- 第11周项目2求两个数的最大公约数
- 多吉美 打工女子捡7万元现金在公交站等失主
- 第11周项目--求四数的最大公约数