二叉树的深度
来源:互联网 发布:淘宝双11整点抢购技巧 编辑:程序博客网 时间:2024/06/05 15:07
题目
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
解题
方法一:递归
/*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 pRoot){ if(pRoot ==null) return 0; int nLeft=TreeDepth(pRoot.left); int nRight=TreeDepth(pRoot.right); return nLeft>nRight?(nLeft+1):(nRight+1); }}
方法二:非递归
求树的高度,换句话就是求树有多少层,可以参考层次遍历算法,我们只需要记录层数
利用队列
每次队列中保存一层的结点
输出一层元素,加入到下一层元素,深度+1
/*public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }};*/import java.util.LinkedList;public class Solution { public int TreeDepth(TreeNode pRoot){ if(pRoot ==null) return 0; LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(pRoot); int depth = 0; while(!queue.isEmpty()){ int size = queue.size(); depth++; while(size-- >0){ TreeNode node = queue.poll(); if(node.left!=null) queue.add(node.left); if(node.right!=null) queue.add(node.right); } } return depth; }}
0 0
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- 二叉树的深度
- jquery延时载入动画焦点图- 有点类似视差动画
- C#表达式和运算符详解
- 面试之我见
- 问题 L: 二叉查找树(Ⅰ)-创建和遍历
- Android SwipeRefreshLayout 官方下拉刷新控件介绍
- 二叉树的深度
- 【智力题】称重问题
- 红黑树
- Hash表分析以及Java实现
- poj-3258-River Hopscotch
- 2016-06-23-课程设计日志
- 《java数据结构与算法》笔记-CH4-8栈结构实现后缀表达式计算结果
- 建assets目录的方法
- compileDebugJavaWithJavac.compileSdkVersion 'android-24' requires JDK 1.8 or later to compile.