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 (object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 myStack = [] node = root treeDepth = 0 maxDepth = 0 while node != None or myStack != []: while node != None: treeDepth += 1 myStack.append((node, treeDepth)) node = node.left now = myStack.pop() node = now[0] maxDepth = max(maxDepth, treeDepth) treeDepth = now[1] node = node.right return maxDepth
|
近期评论