leetcode 111. Minimum Depth of Binary Tree(week 15)

来源:互联网 发布:手机淘宝怎么改价格 编辑:程序博客网 时间:2024/06/06 07:36

题目链接:https://leetcode.com/problems/minimum-depth-of-binary-tree/#/description

这道题目求一棵树的最小深度的问题,这次我们用非递归的方法

经验(非递归方法):

 初始化栈(root,当前高度): while(栈非空):   node = 弹出栈   如果node非空       如果该节点为尾节点:         更新最小高度       左节点压入堆栈(node.left, 当前高度)       右节点压入堆栈(node.right, 当前高度)
stack = [(root, 0)]min = 10000while(stack):    node, current =  stack.pop()    if(node):        if(not node.left and not node.right and  current<min):            min = current + 1        stack.append((node.left, current + 1))         stack.append((node.right, current + 1))
class Solution(object):    def minDepth(self, root):        """        :type root: TreeNode        :rtype: int        """        if(not root):            return 0        else:            return self.dfs(root)    def dfs(self, root):        stack = [(root, 0)]        min = 10000        while(stack):            node, current =  stack.pop()            print(current)            if(node):                if(not node.left and not node.right and  current<min):                    min = current + 1                stack.append((node.left, current + 1))                 stack.append((node.right, current + 1))        return min 
原创粉丝点击