二叉树的深度
来源:互联网 发布:利用淘宝规则赚钱 编辑:程序博客网 时间:2024/06/03 05:03
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
BFS:
/*public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }};*/import java.util.*;public class Solution { public int height = 0; public Queue<TreeNode> q = new LinkedList<TreeNode>(); public Queue<TreeNode> qq = new LinkedList<TreeNode>(); public int TreeDepth(TreeNode pRoot) { if(pRoot == null) return 0; q.add(pRoot); bfs(pRoot); return height; } public void bfs(TreeNode pRoot){ while(!q.isEmpty()){ TreeNode p = q.remove(); if(p.left != null) qq.add(p.left); if(p.right != null) qq.add(p.right); if(q.isEmpty()){ q = qq; qq = new LinkedList<TreeNode>(); height ++; } } }}
DFS:
import java.util.*;public class Solution { public int TreeDepth(TreeNode pRoot) { if(pRoot == null) return 0; int h1 = TreeDepth(pRoot.left); int h2 = TreeDepth(pRoot.right); return 1 + Math.max(h1, h2); }}
0 0
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 使用STM32F1xx_HAL库实现CAN通信的问题
- 逝去的雄心壮志
- 357. Count Numbers with Unique Digits
- JAVA基础6.42——静态代码块
- CCF 网络延迟
- 二叉树的深度
- Sass入门
- C语言之函数printf()的用法
- http://coolxing.iteye.com/blog/1871520/
- Genymotion插件在ADT和Android Studio上安装的问题与解决(2016年9月)
- Linux下搭建个人网站
- 数据结构(一) 线性表、栈和队列
- Android内存优化(使用SparseArray和ArrayMap代替HashMap)
- VMware Workstation上安装Ubuntu 16.04 Server中文版报错:“无法安装busybox-initramfs”