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
                
    
  • 相关阅读:
    面向对象:
    Android体系结构
    面向对象DAO模式
    集合框架
    异常
    面向对象接口
    面向对象多态
    面向对象继承
    面向对象抽象封装
    JDBC
  • 原文地址:https://www.cnblogs.com/absolute/p/5677855.html
Copyright © 2011-2022 走看看