zoukankan      html  css  js  c++  java
  • 【剑指offer】面试题34. 二叉树中和为某一值的路径

    题目描述

    面试题34. 二叉树中和为某一值的路径

    输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
     
    示例:
    给定如下二叉树,以及目标和 sum = 22,
                  5
                 /
                4   8
               /   /
              11  13  4
             /      /
            7    2  5   1

    返回:
    [
       [5,4,11,2],
       [5,8,4,5]
    ]
     

    分析

    思路很简单,可就是自己写不出代码咋整...

    先序遍历,依次加和当前节点val(或减,无所谓),满足和为target以及最后一个节点是叶子结点时返回。

    5 4 11 7 结束后,当前记录的列表不符合要求,应该弹出7 pop然后访问11的右子树2,判断不符合继续pop2 

    抄了解法2,更好懂一点

    解题

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
            res=[]
            temp=[]
            def recur(root,target):
                if(not root):
                    return []
                temp.append(root.val)
                target -=root.val
                if target ==0 and not root.left and not root.right:
                    res.append(temp[:])#深拷贝,因为每次不清空
                recur(root.left, target)
                recur(root.right, target)
                temp.pop()
            recur(root, sum)
            return res

     2.

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:
            # write code here
            if root == None :
                return([])
            res = []
            def dfs(root,road):
                if root.left==None and root.right==None:
                    if sum(road)==target:
                        res.append(road)
                    return 
                if root.left != None: dfs(root.left, road+[root.left.val])
                if root.right != None: dfs(root.right, road+[root.right.val])
            
            dfs(root,[root.val])
            return(res)
  • 相关阅读:
    Func<T>、Action<T> 的区别于说明
    Invoke()/BeginInvoke()区别
    C# Linq处理list数据
    C# 的三种序列化方法
    P3368 【模板】树状数组 2
    P2058 海港
    2019.6.24 校内测试 NOIP模拟 Day 2 分析+题解
    2019.6.20 校内测试 NOIP模拟 Day 1 分析+题解
    2019.6.18 校内测试 分析+题解
    P1310 表达式的值
  • 原文地址:https://www.cnblogs.com/fuj905/p/12917659.html
Copyright © 2011-2022 走看看