【剑指offer】38二叉树的深度

谁借莪1个温暖的怀抱¢ 2023-10-17 21:17 178阅读 0赞
  1. /**
  2. *输入一棵二叉树,求该树的深度。
  3. *从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,
  4. *最长路径的长度为树的深度。
  5. */
  6. import java.util.Queue;
  7. import java.util.LinkedList;
  8. public class Solution {
  9. //递归
  10. public int TreeDepth(TreeNode root) {
  11. if(root == null){
  12. return 0;
  13. }
  14. int left = TreeDepth(root.left);
  15. int right = TreeDepth(root.right);
  16. return Math.max(left, right) + 1;
  17. }
  18. //非递归
  19. public int TreeDepth2(TreeNode root){
  20. if(root == null){
  21. return 0;
  22. }
  23. Queue<TreeNode> queue = new LinkedList<TreeNode>();
  24. queue.add(root);
  25. int depth = 0, count = 0, nextCount = 1;
  26. while(queue.size()!=0){
  27. TreeNode top = queue.poll();
  28. count++;
  29. if(top.left != null){
  30. queue.add(top.left);
  31. }
  32. if(top.right != null){
  33. queue.add(top.right);
  34. }
  35. if(count == nextCount){
  36. nextCount = queue.size();
  37. count = 0;
  38. depth++;
  39. }
  40. }
  41. return depth;
  42. }
  43. public static void main(String[] args) {
  44. Solution s=new Solution();
  45. }
  46. }
  47. class TreeNode {
  48. int val = 0;
  49. TreeNode left = null;
  50. TreeNode right = null;
  51. public TreeNode(int val) {
  52. this.val = val;
  53. }
  54. }

发表评论

表情:
评论列表 (有 0 条评论,178人围观)

还没有评论,来说两句吧...

相关阅读

    相关 offer 深度

    [剑指offer题型分类及各题的代码及解题思路][offer] 1、题目描述 输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树...

    相关 Offer | 深度

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

    相关 offer:深度

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

    相关 Offer-深度

    题目描述 输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 解题思路—使用堆栈:使用堆栈依次压入