104. maximum depth of binary tree

Description

Difficulty: Easy

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Solution

其实只是深度遍历,同时记录深度。
此处使用最简单的中序遍历,stack 在押入节点的同时压入该节点高度,以便取出节点同时恢复高度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class (object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
myStack = []
node = root # working pointer
treeDepth = 0
maxDepth = 0
while node != None or myStack != []:
while node != None: # if still have left child
treeDepth += 1
myStack.append((node, treeDepth))
node = node.left
# run out of lefts
now = myStack.pop()
node = now[0]
maxDepth = max(maxDepth, treeDepth)
treeDepth = now[1]
node = node.right
return maxDepth