Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to parse all paths of python binary tree

Shulou Source: shulou.com Published: 2022-06-01 14:12:01 09月26日 Update

This article is about how to analyze all the paths of the python binary tree. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

Order

Mainly record all the paths of the binary tree

Given a binary tree, the topic 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\ 5 output: ["1-> 2-> 5", "1-> 3"] explain: the path from all root nodes to leaf nodes is: 1-> 2-> 5, 1-> 3 Source: LeetCode link: https://leetcode-cn.com/problems/binary-tree-paths copyright belongs to the collar buckle network. For commercial reprint, please contact official authorization. For non-commercial reprint, please indicate the source. Answer the question / Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode right; * TreeNode (int x) {val = x;} *} * / class Solution {public List binaryTreePaths (TreeNode root) {List result = new ArrayList (); if (root = = null) {return result;} solve (root, ", result); return result } public void solve (TreeNode root, String cur, List result) {if (root = = null) {return;} cur+ = root.val; if (root.left==null & & root.right==null) {result.add (cur); return;} solve (root.left, cur+ "- >", result) Solve (root.right, cur+ "- >", result);}}

Here, using the recursive idea, the solve method is designed, which has a set parameter for collecting the path and another parameter for indicating the path prefix; each time the solve method is executed, the val of the current node is appended to the path prefix, and when the node is a leaf node, the prefix is added to the result and returned; if it is not a leaf node, the-> is concatenated into the path prefix and its left and right child nodes are recursively.

The above is how to analyze all the paths of the python binary tree. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Nodes paths leaves prefixes methods parameters more knowledge articles recursion utility provenance business official that is work meetings ideas articles sources read Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Huawei Redmi Shulou Tech Info Shulou Technology