[leetcode]--104. Maximum Depth of Binary Tree

缺乏、安全感 2022-07-11 14:29 285阅读 0赞

Question 104:

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. package leetcode.common;
  2. /** * 树的节点的定义,Use By 104 */
  3. public class TreeNode {
  4. private int val;
  5. private TreeNode left;
  6. private TreeNode right;
  7. public TreeNode(int x) { val = x; }
  8. public int getVal() {
  9. return val;
  10. }
  11. public void setVal(int val) {
  12. this.val = val;
  13. }
  14. public TreeNode getLeft() {
  15. return left;
  16. }
  17. public void setLeft(TreeNode left) {
  18. this.left = left;
  19. }
  20. public TreeNode getRight() {
  21. return right;
  22. }
  23. public void setRight(TreeNode right) {
  24. this.right = right;
  25. }
  26. }

解决思路:通过递归求二叉树的深度:
(1)root为空则返回零;
(2)root非空则返回 1 + (左子树深度 和 右子树深度 的最大值);

  1. package leetcode;
  2. import leetcode.common.TreeNode;
  3. import utils.LogUtil;
  4. public class Question104 {
  5. /** * 用递归做. * @param root * @return */
  6. public static int maxDepth(TreeNode root) {
  7. if (root == null) return 0;
  8. return 1 + Math.max(maxDepth(root.getLeft()), maxDepth(root.getRight())); //isLeaf is checked here
  9. }
  10. public static void main(String[] args) {
  11. TreeNode root = new TreeNode(0);
  12. root.setLeft(new TreeNode(1));
  13. root.setRight(new TreeNode(2));
  14. TreeNode left1 = root.getLeft();
  15. left1.setLeft(new TreeNode(3));
  16. LogUtil.log_debug("" + maxDepth(root));
  17. }
  18. }

这个例子的运行结果:

  1. 2017-02-02 12:06:313

发表评论

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

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

相关阅读