剑指offer之二叉树的深度
来源:互联网 发布:手机淘宝保证金怎么交 编辑:程序博客网 时间:2024/06/05 18:37
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
/**public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/
递归做法:
public class Solution { public int TreeDepth(TreeNode root) { if(root==null) return 0; return Math.max(TreeDepth(root.left),TreeDepth(root.right))+1; }}
非递归做法[层次遍历]:
import java.util.*;public class Solution { public int TreeDepth(TreeNode root) { if(root == null){ return 0; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); int depth = 0, count = 0, nextCount = 1; while(queue.size()!=0){ TreeNode top = queue.poll(); count++; if(top.left != null){ queue.add(top.left); } if(top.right != null){ queue.add(top.right); } if(count == nextCount){ nextCount = queue.size(); count = 0; depth++; } } return depth; }}
阅读全文
0 0
- 剑指Offer之二叉树的深度
- 剑指offer之二叉树的深度
- 剑指Offer之 - 二叉树的深度
- 剑指offer之二叉树的深度
- 剑指offer系列之三十七:二叉树的深度
- 剑指offer面试题之求二叉树的深度
- 剑指offer系列之37:二叉树的深度
- 剑指offer(四十五)之二叉树的深度
- [剑指offer学习心得]之:二叉树的深度
- 二叉树的深度[剑指offer]之python实现
- 剑指offer之二叉树的深度(Python)
- 【剑指offer】之二叉树深度
- 剑指offer: 二叉树的深度(树)
- 剑指offer--二叉树的深度
- 剑指offer-39 二叉树的深度
- 剑指offer 39 - 二叉树的深度
- 《剑指offer》二叉树的深度
- 剑指 offer:二叉树的深度
- 【笔记】计算机科学导论——数据库概论
- 动态规划-121. Best Time to Buy and Sell Stock
- Java中Object类之finalize()方法的详解
- MQTT入门篇
- Rain on your Parade HDU
- 剑指offer之二叉树的深度
- MySql数据库
- 五 . BeautifulSoup库详解及运用
- NET连接MySQL数据库
- lua脚本学习4
- Unknown column '' in 'field list'解决方案
- 逆欧拉函数
- App installation failed.could not write to the device.
- MVP模式的简单介绍跟简单实现登录功能