zoukankan      html  css  js  c++  java
  • LeetCode:二叉树(一)

    本组囊括二叉树相关题目,难度不等。

     

    思路一:

    DFS。相对于最大深度来说,最小深度需要多考虑一点:即到达节点的其中一个儿子为空另一个非空,需要返回非空儿子的高度+1,作为本节点高度而非返回较小值。这一点解决后就是常规的递归操作了。

     1 class Solution(object):
     2     def minDepth(self, root):
     3         """
     4         :type root: TreeNode
     5         :rtype: int
     6         """
     7         # 做完最大深度来做最小深度
     8         # 思路一:如果按照之前的思路,每次返回较小的高度,难免有点问题
     9         # 具体的话,如果一个节点的其中一个儿子为空,需要返回非空儿子的高度+1,因为另一个就是叶子节点
    10         if not root: 
    11             return 0
    12         left_height = self.minDepth(root.left)
    13         right_height = self.minDepth(root.right)
    14         if not root.left or not root.right: # 叶子节点,如果一个儿子为空那么最小深度肯定就是另一个儿子的高度。
    15             return max(left_height, right_height) + 1
    16         return min(left_height, right_height) + 1

     

    104. Maximum Depth of Binary Tree

    题目描述:简单

    思路一:

    DFS。递归找深度,每次返回子树深度更大的那个;

    递归输入,根节点,输出,这个根节点的树的最大深度

     1 class Solution(object):
     2     def maxDepth(self, root):
     3         """
     4         :type root: TreeNode
     5         :rtype: int
     6         """
     7         
     8         if not root:
     9             return 0
    10         left = self.maxDepth(root.left)
    11         right = self.maxDepth(root.right)
    12 
    13         return max(left, right) + 1 # 返回子树深度更大那个+1

     

    129. Sum Root to Leaf Numbers

    题目描述:简单

    思路一:

    每层需要乘上10,递归实现,考虑dfs;
    用一个sum来保存当前路径的和,用ans来保存当前所有路径的总和;
    每到一个子节点,sum = 子节点的值+sum*10作为当前路径,直到到达叶子节点,ans = ans+sum。

     1 class Solution:
     2     def sumNumbers(self, root: TreeNode) -> int: 
     3         if not root:
     4             return 0
     5         def helper(root, sum): # 递归函数,输入根节点和sum,输出无,不断更新ans
     6             sum = root.val + sum * 10
     7             if not root.left and not root.right:
     8                 self.ans += sum
     9             if root.left:
    10                 helper(root.left, sum)
    11             if root.right:
    12                 helper(root.right, sum)   
    13         self.ans = 0 # 这样也可以定义一个全局变量,只是相对于内层函数dfs
    14         helper(root, 0)
    15         return self.ans
  • 相关阅读:
    Insert into a Binary Search Tree
    Search in a Binary Search Tree
    Binary Search Tree Iterator
    Validate Binary Search Tree
    Serialize and Deserialize Binary Tree
    图的搜索
    codeforce vk cup2017
    hdu1160dp
    完全背包hdu1114
    最长递增子序列hdu1087
  • 原文地址:https://www.cnblogs.com/Jesee/p/13952509.html
Copyright © 2011-2022 走看看