力扣(LeetCode)113

栏目: 数据库 · 发布时间: 6年前

内容简介:题目地址:题目描述:

题目地址:

https://leetcode-cn.com/probl...

题目描述:

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

给定如下二叉树,以及目标和 sum = 22,

5
         / \
        4   8
       /   / \
      11  13  4
     /  \    / \
    7    2  5   1

返回:

[

[5,4,11,2],

[5,8,4,5]

]

解答:

递归。求以root为根并且和为sum的路径等于。

1root为空,那么为空(不存在这个路径)。

2root为叶节点,并且sum等于root.val,返回root这个单节点路径。

3以root的左子树为根并且和为sum-root.val的路径加上root(若该路径存在)。

4以root的右子树为根并且和为sum-root.val的路径加上root(若该路径存在)。

java ac代码:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
     
        List<List<Integer>>ans = new ArrayList(100);
        if(root == null)return ans;
        if(root.left == null && root.right == null && sum == root.val)
        {
            List<Integer> t = new LinkedList();
            t.add(root.val);
            ans.add(t);
            return ans;
        }
        
        List<List<Integer>>t1 = pathSum(root.left,sum-root.val);
        
        List<List<Integer>>t2 = pathSum(root.right,sum-root.val);
        
        if(t1.size() > 0)
        {
            for(int i = 0;i < t1.size();i++)
            {
                LinkedList<Integer>t = (LinkedList)t1.get(i);
                t.addFirst(root.val);
                ans.add(t);
            }
        }
        if(t2.size() > 0)
        {
            for(int i = 0;i < t2.size();i++)
            {
                LinkedList<Integer>t = (LinkedList)t2.get(i);
                t.addFirst(root.val);
                ans.add(t);
            }
        }
        return ans;
        
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Coming of Age in Second Life

Coming of Age in Second Life

Tom Boellstorff / Princeton University Press / 2008-04-21 / USD 29.95

The gap between the virtual and the physical, and its effect on the ideas of personhood and relationships, is the most interesting aspect of Boellstorff's analysis... Boellstorff's portrayal of a virt......一起来看看 《Coming of Age in Second Life》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具