maximum-depth-of-binary-tree

àì夳堔傛蜴生んèń 2021-11-09 08:42 291阅读 0赞

/**
* @author gentleKay
* 题目描述
* Given a binary tree, find its maximum depth.
* The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
* 给定二叉树,求其最大深度。
* 最大深度是从根节点到最远叶节点沿最长路径的节点数。
*/

  1. /**
  2. *
  3. * @author gentleKay
  4. * 题目描述
  5. * Given a binary tree, find its maximum depth.
  6. * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
  7. * 给定二叉树,求其最大深度。
  8. * 最大深度是从根节点到最远叶节点沿最长路径的节点数。
  9. */
  10. public class Main04 {
  11. public static void main(String[] args) {
  12. // TODO Auto-generated method stub
  13. TreeNode root = new TreeNode(4);
  14. root.left = new TreeNode(2);
  15. root.left.left = new TreeNode(1);
  16. root.left.right = new TreeNode(3);
  17. root.right = new TreeNode(6);
  18. root.right.left = new TreeNode(5);
  19. root.right.right = new TreeNode(7);
  20. root.right.right.right = new TreeNode(8);
  21. System.out.println(Main04.maxDepth(root));
  22. }
  23. public static class TreeNode {
  24. int val;
  25. TreeNode left;
  26. TreeNode right;
  27. TreeNode(int x) { val = x; }
  28. }
  29. public static int maxDepth(TreeNode root) {
  30. if (root == null) {
  31. return 0;
  32. }
  33. if (root.left == null) {
  34. return maxDepth(root.right)+1;
  35. }
  36. if (root.right == null) {
  37. return maxDepth(root.left)+1;
  38. }
  39. return Math.max(maxDepth(root.right)+1, maxDepth(root.left)+1);
  40. }
  41. }

  

转载于:https://www.cnblogs.com/strive-19970713/p/11231735.html

发表评论

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

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

相关阅读