LeetCode OJ:Maximum Depth of Binary Tree
来源:互联网 发布:it软件开发是什么 编辑:程序博客网 时间:2024/05/17 22:01
Maximum Depth of Binary Tree
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.
算法思想:
根据层序遍历的思想,将所有元素走完,返回最后的层数就行了
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxDepth(TreeNode *root) { if(!root)return 0; queue<TreeNode *>que; int minLen=0; int curLev=1; int nextLev=0; int depth=0; que.push(root); while(!que.empty()){ TreeNode *cur=que.front(); que.pop(); if(cur->left){que.push(cur->left);nextLev++;} if(cur->right){que.push(cur->right);nextLev++;} if(--curLev==0){ curLev=nextLev; nextLev=0; depth++; } } return depth; }};
递归版
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxDepth(TreeNode *root) { if(!root)return 0; return 1+max(maxDepth(root->left),maxDepth(root->right)); }};
0 0
- [LeetCode OJ]Maximum Depth of Binary Tree
- LeetCode OJ:Maximum Depth of Binary Tree
- LeetCode OJ - Maximum Depth of Binary Tree
- [LeetCode OJ]Maximum Depth Of Binary Tree
- LeetCode OJ Maximum Depth of Binary Tree
- <LeetCode OJ> (104 / 111) Maximum & Minimum Depth of Binary Tree
- LeetCode OJ : 104. Maximum Depth of Binary Tree
- LeetCode oj 104. Maximum Depth of Binary Tree(DFS||BFS)
- 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
- 生成单张表的数据库字典
- jquery插件jTemplates用法
- xcode 5中调试技巧
- C语言之尾队列tailq
- SAP 发送邮件例子(内部)
- LeetCode OJ:Maximum Depth of Binary Tree
- nginx站点配置之域名301重定向
- vs2010 linq语法使用中如果用到外部定义的变量会报错 没有引用对象
- win7 下,安装的VS2008,然后搭配opencv2.3.1运行,报错为:fatal error LNK1112: 模块计算机类型“X86”与目标计算机类型“x64”冲突 。通过网上查询,给错的
- JAVA正则表达式 Pattern和Matcher
- SAP-ABAP程序发送邮件
- 浅析Android4.0 Animator框架
- WEB FORM MVP模式
- oracle显式提交、隐式提交及自动提交