Python programming solution binary tree and a value of the path code example

  • 2020-06-23 00:54:59
  • OfStack

Topic describes

Enter 1 binary tree and 1 integer, and print out the sum of node values in the binary tree as all paths of the input integer. A path is defined as one path from the root of the tree down to the node that the leaf passes through.

First of all, to understand the meaning of the question, from the root node to the child node.

1. If there is only a root node or a leaf node is found, we return the corresponding val value

2. If it is not a leaf node, we recurse the left and right subtrees of the root node until a leaf node is found. Then traversal returns the sequence of val corresponding to leaf node and parent node to the upper level. If you don't find the path, you're actually returning the sequence, just []

The code is as follows:


# -*- coding:utf-8 -*- 
class TreeNode(): 
  def __init__(self,x): 
    self.val = x 
    self.left = None 
    self.right = None 
 
def function(root,target_number): 
  result = [] 
  if not root: 
    return result 
#   If only the root node or the leaf node is found, we return its value  
  if not root.left and not root.right and root.val == target_number: 
    return [[root.val]] 
  else: 
#   If it is not a leaf node, we recurse the left and right subtrees of the root node respectively, and note the modification of variables : 
    left = function(root.left,target_number - root.val) 
    right = function(root.right,target_number - root.val) 
    for item in left+right :  
      result.append([root.val]+item) 
    return result 

conclusion

That's the end of this article on Python programming to solve 2 cross trees and a path with a value of 1. Those who are interested can continue to see this site:

Python Quest creates a 2-cross tree

Python algorithm to calculate the number of n nodes with different 2 tree

If there is any deficiency, please let me know. Thank you for your support!


Related articles: