【LeetCode】剑指 Offer 34. 二叉树中和为某一值的路径

【LeetCode】剑指 Offer 34. 二叉树中和为某一值的路径,第1张

【LeetCode】剑指 Offer 34. 二叉树中和为某一值的路径 【LeetCode】剑指 Offer 34. 二叉树中和为某一值的路径

文章目录
  • 【LeetCode】剑指 Offer 34. 二叉树中和为某一值的路径



package offer;

import java.util.ArrayList;
import java.util.linkedList;
import java.util.List;

//定义树节点
class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(){};

    TreeNode(int x){
        val = x;
    }
}

public class Solution34 {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(5);
        TreeNode node2 = new TreeNode(4);
        TreeNode node3 = new TreeNode(8);
        TreeNode node4 = new TreeNode(11);
        TreeNode node5 = new TreeNode(13);
        TreeNode node6 = new TreeNode(4);
        TreeNode node7 = new TreeNode(7);
        TreeNode node8 = new TreeNode(2);
        TreeNode node9 = new TreeNode(5);
        TreeNode node10 = new TreeNode(1);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node3.left = node5;
        node3.right = node6;
        node4.left = node7;
        node4.right = node8;
        node6.left = node9;
        node6.right = node10;
        Solution34 solution = new Solution34();
        System.out.println(solution.method(node1, 22));
    }

    linkedList> res = new linkedList<>();
    linkedList path = new linkedList<>();

    private List> method(TreeNode root, int sum){
        recur(root, sum);
        return res;
    }

    private void recur(TreeNode root, int tar){
        if(root == null) return;
        path.add(root.val);
        tar -= root.val;
        if(tar == 0 && root.left == null && root.right == null){
            res.add(new linkedList<>(path));
        }
        recur(root.left, tar);
        recur(root.right, tar);
        path.removeLast();
    }
}

//时间复杂度为 O(n)
//空间复杂度为 O(n)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5693027.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存