剑指Offer—38—二叉树的深度
来源:互联网 发布:linux ext3 ext4 区别 编辑:程序博客网 时间:2024/06/08 07:03
二叉树的深度 : 输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
package A38二叉树的最大深度;import java.util.LinkedList;import java.util.Queue;public class Demo { public int TreeDepth(TreeNode pRoot){ if (pRoot == null){ return 0; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(pRoot); int depth = 0; while (!queue.isEmpty()){ depth++; int size = queue.size(); while (size-- > 0){ TreeNode temp = queue.poll(); if (temp.left != null){ queue.add(temp.left); } if (temp.right != null){ queue.add(temp.right); } } } return depth; }}
package A38二叉树的最大深度;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; } int left = TreeDepth(root.left); int right = TreeDepth(root.right); return (left > right) ? (left + 1) : (right + 1); }}
package A38二叉树的最大深度;import java.util.LinkedList;import java.util.Queue;public class Solution1 { // 层次遍历 public int TreeDepth(TreeNode pRoot){ if (pRoot == null){ return 0; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(pRoot); int depth = 0; while (!queue.isEmpty()){ int len = queue.size(); depth++; while (len-- > 0) { // 把队列中的元素吐完 TreeNode top = queue.poll(); if (top.left != null) { queue.add(top.left); } if (top.right != null) { queue.add(top.right); } } } return depth; }}
阅读全文
0 0
- 剑指offer—二叉树的深度
- 剑指offer—二叉树的深度
- 剑指offer — 二叉树的深度
- 剑指Offer——(38)二叉树的深度
- 剑指Offer—38—二叉树的深度
- 剑指offer 38 二叉树的深度
- 《剑指offer》——二叉树的深度
- 《剑指offer》——二叉树的深度
- 剑指offer——二叉树的深度
- 剑指offer——二叉树的深度
- 剑指offer——二叉树的深度
- 剑指offer——38.二叉树的深度
- 剑指offer——二叉树的深度与平衡二叉树的判断
- 剑指offer: 二叉树的深度(树)
- 剑指Offer之二叉树的深度
- 剑指offer--二叉树的深度
- 剑指offer之二叉树的深度
- 剑指Offer之 - 二叉树的深度
- 算法题之-数组合并排序
- update on duplicate key update
- android 检测网络
- Hackerrank Magic Cards
- sql面试题及答案总结
- 剑指Offer—38—二叉树的深度
- 51nod 2006 飞行员配对(二分图最大匹配)
- 不具参考价值--struts2 那个啥
- 位运算实现两个整数的加法运算
- hdu6181Two Paths(次短路模板题)
- Spring笔记-通过Spring的配置文件来配置bean
- Salty Fish
- Path Sum,Path Sum II,Path Sum III总结
- 并发编程-synchronized的实现原理和应用