Prove safety and offer to a certain value in the binary tree path python

Title Description

An input binary tree root node and an integer, the binary print values ​​of nodes in the input path and all integers. Forming a path to the path definition begins from the root node of the tree down to the leaf node has been traversed nodes. (Note: the return value in the list, a large array Array front)

Thinking

Backtracking, define a current path, and all paths.

Code

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def __init__(self):
        self.onePath =[]
        self.allPath = []
     # return to two-dimensional list, found inside each list represents the path 
    DEF FindPath (Self, root, expectNumber):
         # the Write code here Wallpaper 
        IF  not root:
             return self.allPath
        self.onePath.append(root.val)
        expectNumber -= root.val
        if not root.left and not root.right and expectNumber == 0:
            self.allPath.append(self.onePath[:])
        elif expectNumber > 0:
            self.FindPath(root.left,expectNumber)
            self.FindPath(root.right,expectNumber)
        self.onePath.pop()
         
        return self.allPath

 

Guess you like

Origin www.cnblogs.com/wangzhihang/p/11792920.html