Maximum Depth of Binary Tree

题目分析

原题链接,登陆 LeetCode 后可用
这道题让我们找一棵二叉树的最大深度,可以用递归的思路去解这道题,原问题可以分解为先求左右子树的最大深度,然后加上 1 即是整棵二叉树的最大深度。那么左右子树依此类推。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) {
            return 0;
        } else {
            int lmd = maxDepth(root.left);
            int rmd = maxDepth(root.right);
            return (lmd > rmd) ? lmd + 1 : rmd + 1;
            // return Math.max(lmd, rmd) + 1;
            // if(lmd > rmd){
            //     return lmd + 1;
            // } else {
            //     return rmd + 1;
            // }
        }
    }
}

你可能感兴趣的:(Maximum Depth of Binary Tree)