LeetCode-104. Maximum Depth of Binary Tree
来源:互联网 发布:如何取消淘宝店铺差评 编辑:程序博客网 时间:2024/06/05 14:51
104. 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.
就是求二叉树的最深深度,BFS,DFS应该都可以。
class Solution { public int maxDepth(TreeNode root) { if(root==null){ return 0; } return 1+Math.max(maxDepth(root.left),maxDepth(root.right)); }}
public int maxDepth(TreeNode root) { //DFS if(root == null) { return 0; } Stack<TreeNode> stack = new Stack<>(); Stack<Integer> value = new Stack<>(); stack.push(root); value.push(1); int max = 0; while(!stack.isEmpty()) { TreeNode node = stack.pop(); int temp = value.pop(); max = Math.max(temp, max); if(node.left != null) { stack.push(node.left); value.push(temp+1); } if(node.right != null) { stack.push(node.right); value.push(temp+1); } } return max;}
public int maxDepth(TreeNode root) {//BFS if(root == null) { return 0; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int count = 0; while(!queue.isEmpty()) { int size = queue.size(); while(size-- > 0) { TreeNode node = queue.poll(); if(node.left != null) { queue.offer(node.left); } if(node.right != null) { queue.offer(node.right); } } count++; } return count;}
阅读全文
0 0
- [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
- LeetCode 104. 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 LeetCode
- 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
- 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
- Leetcode 104. Maximum Depth of Binary Tree
- LeetCode *** 104. Maximum Depth of Binary Tree
- git tag与git tag -a的不同
- “北京时间”全站HTTPS加密,引领新闻网站加密趋势
- 设计模式--责任链模式
- path-sum Java code
- OpenCV实现彩色点的实时追踪
- LeetCode-104. Maximum Depth of Binary Tree
- 先到先服务(FCFS)算法C语言,Java语言实现
- OpenCV直方图计算,以及颜色迁移
- QGis二次开发基础 -- 添加矢量要素功能
- 【二分法】LeetCode-Search Insert Position
- 拉格朗日对偶
- activity与fragment的区别
- [LeetCode]19. Remove Nth Node From End of List
- Linux 网络栈剖析