zoukankan      html  css  js  c++  java
  • 513. 找树左下角的值





    方法一:BFS模板的应用。

    总结的DFS、BFS模板参考:https://www.cnblogs.com/panweiwei/p/13065661.html

    class Solution(object):
        # BFS
        def findBottomLeftValue(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if not root:
                return
            res = []
            stack = [root]
            while stack:
                sizestack = len(stack)
                temp = []
                for i in range(sizestack):
                    node = stack.pop(0)
                    temp.append(node.val)
                    if node.left:
                        stack.append(node.left)
                    if node.right:
                        stack.append(node.right)
                res.append(temp)
            return res[-1][0]
    

    BFS方法的改进:层序时先右后左,直接返回最后一个节点的值。

    class Solution(object):
        # BFS改进
        def findBottomLeftValue3(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if not root:
                return
            stack = [root]
            while stack:
                node = stack.pop(0)
                if node.right:
                    stack.append(node.right)
                if node.left:
                    stack.append(node.left)
            return node.val
    

    方法二:DFS模板的应用。

    class Solution(object):
        # DFS
        def findBottomLeftValue2(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
    
            def dfs(node, curdepth):
                if not node:
                    return
                if curdepth > self.maxdepth:
                    self.res = node.val
                    self.maxdepth = curdepth
                dfs(node.left, curdepth + 1)
                dfs(node.right, curdepth + 1)
    
            self.maxdepth, self.res = 0, root.val
            dfs(root, 0)
            return self.res
    
  • 相关阅读:
    人月神话阅读笔记
    12周总结
    IOS成长之路-用NSXMLParser实现XML解析
    沟通能力的表达
    IOS中UIScrollView的contentSize、contentOffset和contentInset属性
    Block 的使用时机
    drawAdapter
    drawpoly()函数的用法
    @synchronized(self)
    Swift2
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13661659.html
Copyright © 2011-2022 走看看