111. Minimum Depth of Binary Tree
来源:互联网 发布:sql 年月日变成日期 编辑:程序博客网 时间:2024/06/13 23:01
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
问题:找最小深度
思想:104题是找最大深度
(1)递归:根节点的左孩子为空时返回右子树的最小深度+1,当右孩子为空时返回左子树的最小深度+1,当左右孩子均存在时返回左右子树最小深度值+1
(2)队列:借助队列,类似于按照层次查找,出队得到节点node,如果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 minDepth(TreeNode root){ if(root==null) return 0; int dep=1; Queue<TreeNode> q=new LinkedList(); q.add(root); while(!q.isEmpty()){ int size=q.size(); for(int i=0;i<size;i++){ TreeNode node=q.poll(); if(node.left==null &&node.right==null) return dep; if(node.left!=null) q.add(node.left); if(node.right!=null) q.add(node.right); } dep++; } return dep; }}
public int minDepth(TreeNode root) { if(root==null) return 0; if(root.left==null&&root.right==null)return 1; if(root.left==null) return minDepth(root.right)+1; if(root.right==null) return minDepth(root.left)+1; return Math.min(minDepth(root.right)+1, minDepth(root.left)+1); }
0 0
- LeetCode 111. Minimum Depth of Binary Tree
- [LeetCode]111.Minimum Depth of Binary Tree
- 【LeetCode】111.Minimum Depth of Binary Tree
- [Leetcode] 111. Minimum Depth of Binary Tree
- 111.Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- [leetcode] 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree LeetCode
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 【LeetCode】111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- Android编程权威指南(第二版)学习笔记(二十九)—— 第29章 定制视图与触摸事件
- windows下使用C++访问redis
- Java使用库函数排序
- Java未来的应用前景
- 利用python制作直方图
- 111. Minimum Depth of Binary Tree
- 【加密】Cocos2d-x PNG图片资源加密(修改版)
- sqlserver如何通过管理器设置字段的自增
- axios的使用
- ECharts简单使用
- C++之this指针
- python3.x编程模板总结
- 智联招聘可以登录,发帖纪念一下
- ARM汇编指令