边工作边刷题:70天一遍leetcode: day 16-1
Minimum Depth of Binary Tree
同理,这题用preorder iterative搞定。注意即使是preorder一个高度变量是不够的。因为在同一高度同时入栈左右,左边出栈后并不知道当前栈内的是右子树还是上一层。这样就没法用同一个变量track height了
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
stk = [(root, 1)]
mh = sys.maxint
while stk:
cur = stk[-1][0]
h = stk[-1][1]
stk.pop()
more = False
if cur.right:
stk.append((cur.right, h+1))
more = True
if cur.left:
stk.append((cur.left, h+1))
more = True
if not more:
if h<mh:
mh = h
return mh