104. 二叉树的最大深度

递归解决

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
  int res = 0;
    public int maxDepth(TreeNode root) {
        if(root==null)
            return 0;
        depth(root,1);
        return res;
    }
    public void depth(TreeNode root, int i) {
        if (root.left != null) {
            depth(root.left,i+1);
        }
        if (root.right!= null) {
            depth(root.right,i+1);
        }
        this.res = Math.max(i, res);
    }
}

别的解法太精炼了

/**
 * 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;
        return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
    }
}
全部评论

相关推荐

下北澤大天使:你是我见过最美的牛客女孩😍
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务