递归真的懂了呀系列《自底向上:二叉树的最大深度》

66 阅读1分钟

Problem: 104. 二叉树的最大深度

讲述看到这一题的思路

递归:自底向上,每一层考虑左右子树深度最大值,返回结果时+1(当前节点长度为1)

Code

/**
 * 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;
        int l = maxDepth(root.left);
        int r = maxDepth(root.right);
        return Math.max(l,r)+1;
    }
}