Wins the Offer (XXIV): a binary tree and a path value

Wins the Offer (XXIV): a binary tree and a path value

Search micro-channel public number: 'AI-ming3526' or 'this small computer vision' for more algorithms, machine learning, dry
CSDN: https://blog.csdn.net/baidu_31657889/
GitHub: https://github.com/ aimi-cn / AILearners

First, the primer

This series is my brush "to prove safety Offer" brush off the cattle in question notes online, it aims to enhance the ability under its own algorithm.
View the complete algorithm to prove safety issues resolved Offer Click: to prove safety Offer complete analytical exercises

Second, the title

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)

1, ideas

Two global variables result and tmp, result to hold the final result, tmp for storing temporary results.

Every traversal, we first root value stitching to tmp, and then determine whether the current root meet:

  • Left subtree is not empty
  • Right subtree is not empty
  • And whether the result of splicing and values ​​are equal expectNumber

If the condition is satisfied, it will result in splicing tmp, otherwise, turn left and right sub-tree traversal. Note that, when the left and right sub-tree traversal, global variable tmp is backtracking to do, because if the path of a leaf node and does not meet the requirements we going back? This is not necessary to wipe off the leaf node and then back to the parent node to another child node access.

2, programming

python

Code implementation:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回二维列表,内部每个列表表示找到的路径
    def FindPath(self, root, expectNumber):
        # write code here
        def subFindPath(root):
            if root:
                tmp.append(root.val)
                if not root.right and not root.left and sum(tmp) == expectNumber:
                    result.append(tmp[:])
                else:
                    subFindPath(root.left),subFindPath(root.right)
                # 回溯
                tmp.pop()
        result, tmp = [], []
        subFindPath(root)
        sorted(result, key=len, reverse=True)
        return result

AIMI-CN AI learning exchange group [1015286623] for more information on AI

Sharing technology, fun in life: our number of public computer vision this small push "AI" series News articles per week, welcome your interest!

Guess you like

Origin www.cnblogs.com/aimi-cn/p/11433518.html