zoukankan      html  css  js  c++  java
  • 边工作边刷题: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
                
    
  • 相关阅读:
    Ensp模拟OSPF与ACL综合应用
    ENSP配置NAT
    Ensp配置RSTP
    EnspOSPF单区域配置
    Ensp配置静态路由和默认路由
    NotPron国外版
    MSF
    转换流
    梦之光芒1-14关通关秘籍
    php序列化与反序列化
  • 原文地址:https://www.cnblogs.com/absolute/p/5677855.html
Copyright © 2011-2022 走看看