algorithm notes: leetcode#104 maximum depth of binary tree

Problem


Solution


Analysis

Python implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
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).


104. Maximum Depth of Binary Tree
(中文版) 算法笔记: 力扣#104 二叉树的最大深度