【数据结构与算法】深度优先搜索

深度优先搜索

例题

Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7
Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4
Return false.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        def dfs(root):
            if root is None:
                return True, 0
            left_flag, left_height = dfs(root.left)
            right_flag, right_height = dfs(root.right)
            
            if left_flag and right_flag and abs(left_height-right_height)<2:
                return True, max(left_height, right_height)+1
            else:
                return False, -1
        ans, _ = dfs(root)
        return ans

Binary Tree Maximum Path Sum

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6
Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

返回连接根节点的最大和
在不断迭代过程中就开始比较,维护一个最大值。

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
    def maxPathSum(self, root: TreeNode) -> int:
        self.ans = -float('inf')
        def dfs_sum(root):

            if root is None:
                return -float('inf')
            
            left_max = dfs_sum(root.left)
            right_max = dfs_sum(root.right)

            self.ans = max(self.ans,
                           root.val,
                              left_max, 
                              right_max, 
                              left_max + root.val, 
                              right_max + root.val, 
                              left_max + root.val + right_max)
            
            return max(root.val, root.val + left_max, root.val + right_max)
        
        dfs_sum(root)
        return self.ans

Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1
Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

对于只计算到叶节点的,要注意当计算到叶节点的时候就输出结果,不能到叶节点的左右空结点再输出!

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
    def pathSum(self, root: TreeNode, sum_: int) -> List[List[int]]:
        self.ans = []
        
        def dfs(root, path):
            if root is None:
                return
            if root.left is None and root.right is None:
                if sum(path+[root.val]) == sum_:
                    self.ans.append(path+[root.val])
                return

            dfs(root.left, path+[root.val])
            dfs(root.right, path+[root.val])
        
        dfs(root, [])
        return self.ans
全部评论

相关推荐

喜欢吃蛋糕仰泳鲈鱼是我的神:字节可以找个hr 给你挂了,再放池子捞
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务