美文网首页
二叉树中和为某一值的路径

二叉树中和为某一值的路径

作者: momo1023 | 来源:发表于2019-03-27 18:41 被阅读0次
    # -*- coding:utf-8 -*-
    
    import copy
    # 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
            result=[]
            if not root:
                return result
            
            def FindPathCore(root, path, curNumber):
                curNumber += root.val
                path.append(root.val)
                if curNumber == expectNumber and not root.left and not root.right:
                    # onepath=[]
                    # for item in path:
                    #     onepath.append(item)
                    # result.append(onepath)
                    result.append(copy.deepcopy(path))
                if curNumber < expectNumber:
                    if root.left:
                        FindPathCore(root.left, path, curNumber)
                    if root.right:
                        FindPathCore(root.right, path, curNumber)
                path.pop()
            
            path = []
            curNumber = 0
            FindPathCore(root, path, curNumber)
            return result
    

    相关文章

      网友评论

          本文标题:二叉树中和为某一值的路径

          本文链接:https://www.haomeiwen.com/subject/czetbqtx.html