Problem
Solution
Analysis
Python implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class : def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
|
Java implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
* Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class { public int maxDepth(TreeNode root) { if(root == null){ return 0; } int leftDepth = maxDepth(root.left); int rightDepth = maxDepth(root.right); return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1; } }
|
Time complexity
O(N).
Space complexity
O(N).
Links
104. Maximum Depth of Binary Tree
(中文版) 算法笔记: 力扣#104 二叉树的最大深度
近期评论