当前位置:  首页>> 技术小册>> 数据结构与算法(中)

题目描述

输入一棵二叉树的根结点,求该树的深度。

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

样例

  1. 输入:二叉树[8, 12, 2, null, null, 6, 4, null, null, null, null]如下图所示:
  2. 8
  3. / \
  4. 12 2
  5. / \
  6. 6 4
  7. 输出:3

解法

递归即可。

  1. /**
  2. * @author bingo
  3. * @since 2018/12/10
  4. */
  5. /**
  6. * Definition for a binary tree node.
  7. * public class TreeNode {
  8. * int val;
  9. * TreeNode left;
  10. * TreeNode right;
  11. * TreeNode(int x) { val = x; }
  12. * }
  13. */
  14. class Solution {
  15. /**
  16. * 求二叉树的深度
  17. *
  18. * @param root 二叉树根结点
  19. * @return 深度
  20. */
  21. public int treeDepth(TreeNode root) {
  22. if (root == null) {
  23. return 0;
  24. }
  25. int lDepth = treeDepth(root.left);
  26. int rDepth = treeDepth(root.right);
  27. return 1 + Math.max(lDepth, rDepth);
  28. }
  29. }

测试用例

  1. 功能测试(输入普通的二叉树;二叉树中所有节点都没有左/右子树);
  2. 特殊输入测试(二叉树只有一个节点;二叉树的头节点为空指针)。

该分类下的相关小册推荐: