力扣104 二叉树的最大深度

题目:

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3

思路:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null){
            return 0;
        }else{
            return getDepth(root.left,root.right);
        }
    }

    public int getDepth(TreeNode left,TreeNode right){//1.确定参数和返回值
        int count=1;
        if(left==null&&right==null){//2.确定终止条件
            return 1;
        }
        if(left!=null&&right==null){
            count=getDepth(left.left,left.right)+1;
        }
        if(left==null&&right!=null){
            count=getDepth(right.left,right.right)+1;
        }
        if(left!=null&&right!=null){
            int count1=getDepth(left.left,left.right)+1;//3.确定单层逻辑
            int count2=getDepth(right.left,right.right)+1;
            count=count1>count2?count1:count2;
        }
        return count;
    }
}

 改进:

class Solution {
    public int maxDepth(TreeNode root) {
       if(root==null){
           return 0;
       }
       int count1=maxDepth(root.left)+1;
       int count2=maxDepth(root.right)+1;
       return count1>count2?count1:count2;
    }
}

 

posted @ 2023-01-27 22:13  壹索007  阅读(20)  评论(0)    收藏  举报