LeetCode-Maximum Depth of Binary Tree

Bertha 。 2022-08-09 03:14 112阅读 0赞
  • Problem:

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.

  • analysis:

利用递归求左节点和右节点较大值,然后再加一。

  • anwser:
  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public int maxDepth(TreeNode root) {
  12. int leftMaxDepth,rightMaxDepth;
  13. if(root == null) return 0;
  14. leftMaxDepth = maxDepth(root.left);
  15. rightMaxDepth = maxDepth(root.right);
  16. return max(leftMaxDepth,rightMaxDepth) + 1;
  17. }
  18. public int max(int a,int b){
  19. if(a>b) return a;
  20. else return b;
  21. }
  22. }

发表评论

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

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

相关阅读