LeetCode

链接

104. Maximum Depth of Binary Tree

题意

给定一个二叉树,求它的最大深度(也就是高)

思路

利用递归,求每个节点的最大深度,累加起来即可

代码

Java:

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

总结

+1是因为当前节点未计算入内

效率

Your runtime beats 18.63% of java submissions

原文地址:https://www.cnblogs.com/zyoung/p/6651914.html