104. Maximum Depth of Binary Tree (Easy)
来源:互联网 发布:手机淘宝店名可以改吗 编辑:程序博客网 时间:2024/06/13 09:05
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.
题目即求二叉树的高度,层序遍历二叉树求解即可。
Solution:
Java:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int maxDepth(TreeNode root) { if(root == null) { return 0; } if(root.left == null && root.right == null) { return 1; } int maxDepth = 0; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int currentLevelCount = 1; int nextLevelCount = 0; while(!queue.isEmpty()) { TreeNode node = queue.poll(); currentLevelCount--; if(node.left != null) { queue.add(node.left); nextLevelCount++; } if(node.right != null) { queue.add(node.right); nextLevelCount++; } if(currentLevelCount == 0) { currentLevelCount = nextLevelCount; nextLevelCount = 0; maxDepth++; } } return maxDepth; }}
非递归的层序遍历,通过队列来实现,使用currentLevelCount和nextLevelCount两个变量记录当前层的结点个数和下一层的结点个数。
0 0
- 104. Maximum Depth of Binary Tree (Easy)
- 【leetcode】【Easy】【104. Maximum Depth of Binary Tree】【tree】
- Maximum Depth of Binary Tree(easy)
- Leetcode----104. Maximum Depth of Binary Tree(easy)
- 104. Maximum Depth of Binary Tree [easy] (Python)
- Easy-题目3:104. Maximum Depth of Binary Tree
- Leetcode 104. Maximum Depth of Binary Tree (Easy) (cpp)
- LeetCode解题报告 104. Maximum Depth of Binary Tree [easy]
- [Leetcode 104, Easy] Minimum (Maximum) Depth of Binary Tree
- 【LeetCode】(104)Maximum Depth of Binary Tree(Easy)
- Easy 104题 Maximum Depth of Binary Tree
- LeetCode #104 - Maximum Depth of Binary Tree - Easy
- Maximum Depth of Binary Tree——Difficulty:Easy
- 【Leetcode-easy-104】Maximum Depth of Binary Tree
- LeetCode-Easy刷题(21) Maximum Depth of Binary Tree
- [LeetCode]104.Maximum Depth of Binary Tree
- 104.Maximum Depth of Binary Tree
- 【LeetCode】104.Maximum Depth of Binary Tree
- eclipse不能自动编译生成class文件的解决办法
- BZOJ4715 囚人的旋律
- explicit in c++
- 电商大战的背后,需要怎样的技术支撑?
- Open CV学习记录(十九)—图片拼接
- 104. Maximum Depth of Binary Tree (Easy)
- 盘点当下最流行的 Java 工具
- Android Studio离线使用gradle
- 一些实用的 Laravel 小技巧
- slice()截取方法substring()字符串截取substr()字符串截取
- 黑马程序员:各学科学习路线图,简直是厉害了word哥
- PHP设计模式之:单例模式
- UCOS-III 消息队列正确使用方法
- T-SQL