How to find all the paths and sums of python binary trees
How to find all the paths and sums of python binary tree, I believe that many inexperienced people do not know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
All paths of the binary tree and
The requirement becomes the path sum based on 257.
Given a binary tree, returns all paths from the root node to the leaf node. Note: a leaf node is a node that does not have child nodes.
Example:
Input
1 /
2 3
five
Output: ["1-> 2-> 5", "1-> 3"]
Explanation: the path from all root nodes to leaf nodes is: 1-> 2-> 5, 1-> 3
Code thinking
Dfs
Leaf node, get the path of this branch, sum
Summarize all paths and
#! / usr/bin/env python "" doc: "" from typing import List, Set# Definition for a binary tree node.class TreeNode: def _ _ init__ (self, x): self.val = x self.left = None self.right = Noneclass Solution: def dfs (self, root: TreeNode, path: List [str] Path_map: List [str]): if not root: return None path.append (root.val) if root.left is None and root.right is None: # path_str = "- >" .join (path) path_sum = sum (path) print (Flemish-> cur leaf path: {path} sum: {path_sum}') Path_map.append (path_sum) return self.dfs (root.left List (path), path_map) self.dfs (root.right, list (path), path_map) def binaryTreePaths (self, root: TreeNode)-> List [str]: path = [] path_map = [] self.dfs (root, path) Path_map) return sum (path_map) def main (): root = TreeNode (1) node_2 = TreeNode (2) root.left = node_2 root.right = TreeNode (3) node_2.right = TreeNode (5) ret = Solution (). BinaryTreePaths (root) print (ret) if _ name__ = ='_ main__': main () read the above Do you know how to find all the paths and sums of python binary trees? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!