Wins the offer - to find path

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

And to do this before in a leetcode find all the possible combinations of numbers like. Recursive, but remember to add it to determine whether the leaf nodes come

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def FindPath(self, root, target):
        anslist = []
        if root:
            if root.val < target:
                left = self.FindPath(root.left,target-root.val)
                right = self.FindPath(root.right,target-root.val)
                if left:
                    anslist += [[root.val]+ans for ans in left]
                if right>0:
                    anslist += [[root.val]+ans for ans in right]
                return anslist
            elif root.val == target:
                if root.left or root.right:
                    return []
                else:
                    return [[root.val]]
        else:
            return []

 

Another idea

Find all the path from the root to the leaves, then add the path and see whether the target. Here traversal and depth that question before leetcode like. With three variables

The first variable root

Second variable store all Paths, each address of the array is transmitted, directly modify the contents of the array

The third variable holds the current path, once the leaf node is reached, the path is stored in the paths go.

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def FindPath(self, root, target):
        if not root:
            return []
        paths = self.DFS(root,[],[root.val])
        ans = []
        for path in paths:
            if sum(path) == target:
                ans.append(path)
        return ans
    
    # 这里注意一下,之前写的不顺
    def DFS(self,root,result,path):
        if root.left == None and root.right==None:
            result.append(path)
        if root.left:
            self.DFS(root.left,result,path+[root.left.val])
        if root.right:
            self.DFS(root.right,result,path+[root.right.val])
        return result

 

Published 82 original articles · won praise 2 · Views 4364

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104745044