In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
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!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.