LeetCode 二叉树中的路径总和问题(判断以及列出所有路径)、二叉树的所有路径、二叉树中的最大路径和

  • Post author:
  • Post category:其他




LeetCode 112. 路径总和

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。


说明: 叶子节点是指没有子节点的节点。

示例:

给定如下二叉树,以及目标和 sum = 22,

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

返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。



解题思路:递归

最直接的方法就是利用递归,遍历整棵树:如果当前节点不是叶子,对它的所有孩子节点,递归调用 hasPathSum 函数,其中 sum 值减去当前节点的权值;如果当前节点是叶子,检查 sum 值是否为 0,也就是是否找到了给定的目标和。


Python代码实现如下:

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

class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        if not root:
            return False
        if not root.left and not root.right and sum == root.val:
            return True
        left = self.hasPathSum(root.left, sum-root.val)
        right = self.hasPathSum(root.right, sum-root.val)
        return left or right



113. 路径总和 II

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

示例 1:

输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22

输出:[[5,4,11,2],[5,8,4,5]]

示例 2:

输入:root = [1,2,3], targetSum = 5

输出:[]

示例 3:

输入:root = [1,2], targetSum = 0

输出:[]

提示:

树中节点总数在范围 [0, 5000] 内

-1000 <= Node.val <= 1000

-1000 <= targetSum <= 1000

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
        if not root:
            return []
        if not root.left and not root.right and targetSum==root.val:
            return [[root.val]]
        res = []
        left = self.pathSum(root.left, targetSum-root.val)
        right = self.pathSum(root.right, targetSum-root.val)
        for i in left+right:
            res.append([root.val] + i)
        return res



LeetCode 257. 二叉树的所有路径

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

         1
       /   \
      2     3
        \
         5

输出: [“1->2->5”, “1->3”]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

解题方法与上题类似:递归与迭代

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

class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        if not root:
            return []
        res, queue = [], collections.deque()
        queue.appendleft([root, []])
        while queue:
            node, tmp = queue.pop()
            if not node.left and not node.right:
                res.append("->".join(tmp + [str(node.val)]))
            if node.left: queue.appendleft([node.left, tmp + [str(node.val)]])
            if node.right: queue.appendleft([node.right, tmp + [str(node.val)]])
        return res

  • 不使用双端队列
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        def construct(root, path):
            if root is None:
                return None
            path += str(root.val)
            if(root.left is None and root.right is None):
                paths.append(path)
            else:
                path += '->'
                construct(root.left, path)
                construct(root.right, path)

        paths = []
        path = ''
        construct(root, path)

        return paths
  • C++实现:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
     void construct_paths(TreeNode* root, string path, vector<string>& paths) {
        if (root != nullptr) {
            path += to_string(root->val);
            if (root->left == nullptr && root->right == nullptr) {  // 当前节点是叶子节点
                paths.push_back(path);                              // 把路径加入到答案中
            } else {
                path += "->";  // 当前节点不是叶子节点,继续递归遍历
                construct_paths(root->left, path, paths);
                construct_paths(root->right, path, paths);
            }
        }
    }

    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> paths;
        construct_paths(root, "", paths);
        return paths;
    }
      
};



124. 二叉树中的最大路径和(困难)

路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。

路径和 是路径中各节点值的总和。

给你一个二叉树的根节点 root ,返回其 最大路径和 。

输入:root = [1,2,3]

输出:6

解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6

输入:root = [-10,9,20,null,null,15,7]

输出:42

解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42

解题方法:动态规划 or 递归

  • 代码如下:
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxPathSum(self, root: TreeNode) -> int:
        self.res = -sys.maxsize
        self.dfs(root)
        return self.res
    def dfs(self, root):
        if not root:
            return 0
        max_num = root.val
        l_max_num = self.dfs(root.left)
        r_max_num = self.dfs(root.right)
        max_num = max(max_num, max_num + l_max_num)
        max_num = max(max_num, max_num + r_max_num) 
        self.res = max(self.res, max_num)
        return max(0, l_max_num,r_max_num) +root.val
  • C++
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxPathSum(TreeNode* root) {
        dfs(root);
        return res;
    }
    int dfs(TreeNode* root){
        if(root == NULL){
            return 0;
        }
        int max_sum = root->val;
        int l_max_sum = dfs(root->left);
        int r_max_sum = dfs(root->right);
        max_sum = max(max_sum, max_sum+ l_max_sum);
        max_sum = max(max_sum, max_sum + r_max_sum);
        res = max(res, max_sum);
        return max({0, l_max_sum, r_max_sum}) + root->val;
    }
private:
    int res = INT_MIN;
};



版权声明:本文为mrjkzhangma原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。