104. Maximum Depth of Binary Tree
来源:互联网 发布:java开发单元测试 编辑:程序博客网 时间:2024/04/30 05:57
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 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) { return root == null? 0: Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; }}另外这道题也可以用BFS和DFS来做,代码如下:
DFS
public int maxDepth(TreeNode root) { 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;}// 7ms
BFS
public int maxDepth(TreeNode root) { 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;}// 3ms
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
- 1100. Mars Numbers (20)
- jieba和朴素贝叶斯实现文本分类
- LeetCode 206. Reverse Linked List
- C#中stringBuilder和string的区别
- 【Matlab Computer Vision System ToolBox】学习笔记-1-点云配准流程 | 特征匹配
- 104. Maximum Depth of Binary Tree
- 我们公司(创业公司)目前的组织架构-部门划分和部门职能
- java集合使用方法
- 检测Android系统是否是MIUI
- Nginx反向代理、CORS、JSONP等跨域请求解决方法总结
- Django south 使用指南
- HDU 1073 内容相等判断
- java基础篇笔记<二>
- system表空间用满解决 方法