您现在的位置是:首页 > 文章详情

[剑指offer] 二叉树的深度

日期:2018-07-28点击:320

本文首发于我的个人博客:尾尾部落

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

解题思路

法一:递归法。求二叉树的深度,就是求左子树、右子树的中深度最大的加上一个根节点,依此递归即可。
法二:层次遍历。每遍历一层,deep 加 1,直接到最后一层,输出 deep。

参考代码

法一:递归法

/** 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; int left = TreeDepth(root.left) + 1; int right = TreeDepth(root.right) + 1; return left > right ? left : right; } } 

法二:层次遍历

import java.util.Queue; import java.util.LinkedList; public class Solution { public int TreeDepth(TreeNode root) { if(root == null) return 0; int deep = 0; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); int start = 0, end = 1; while(!queue.isEmpty()){ TreeNode node = queue.poll(); start ++; if(node.left != null){ queue.offer(node.left); } if(node.right != null){ queue.offer(node.right); } if(start == end){ end = queue.size(); start = 0; deep ++; } } return deep; } } 
原文链接:https://yq.aliyun.com/articles/642753
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章