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

吞佛童子2022年10月10日
  • algorithm
  • Tree
小于 1 分钟

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

难度: 🌕

问题描述

img_45.png


解法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        // 思路:
        // 回溯
        LinkedList<Integer> path = new LinkedList<>();
        mySol(root, target, 0, path);
        return res;
    }

    private void mySol(TreeNode cur, int target, int preVal, LinkedList<Integer> path) {
        // 递归终止条件
        if(cur == null) {
            return;
        }
        if(cur.left == null && cur.right == null) {
            if(preVal + cur.val == target) {
                path.addLast(cur.val);
                res.add(new LinkedList<>(path));
                path.removeLast();
            }
            return;
        }
        // 非叶子节点,继续往下
        path.addLast(cur.val);
        mySol(cur.left, target, preVal + cur.val, path);
        mySol(cur.right, target, preVal + cur.val, path);
        path.removeLast();
    }
}

输出

img_44.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou