Skip to content

Latest commit

 

History

History
97 lines (83 loc) · 2.85 KB

437_路径总和III.md

File metadata and controls

97 lines (83 loc) · 2.85 KB
import java.util.*;

/**
 * @author : xfhy
 * Create time : 2020年10月27日12:34:21
 * Description : 437. 路径总和 III
 * source : https://leetcode-cn.com/problems/path-sum-iii/
 */
public class Solution {

    public static 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;
        }

        @Override
        public String toString() {
            return "TreeNode{" +
                    "val=" + val +
                    ", left=" + left +
                    ", right=" + right +
                    '}';
        }
    }

    /**
     * 思路:求 当前节点的路径个数+左节点路径个数+右节点路径个数
     *
     * 1.以当前节点作为头结点的路径数量
     * 2.以当前节点的左孩子作为头结点的路径数量
     * 3.以当前节点的右孩子作为头结点的路径数量
     *
     */
    public static int pathSum(TreeNode root, int sum) {
        if (root == null) {
            return 0;
        }
        //当前节点的路径个数+左节点路径个数+右节点路径个数
        int result = countPath(root, sum);
        int a = pathSum(root.left, sum);
        int b = pathSum(root.right, sum);
        return result + a + b;

    }

    //统计root为根节点,往下,有没有一条路径和为sum
    public static int countPath(TreeNode root, int sum) {
        if (root == null) {
            return 0;
        }
        sum = sum - root.val;
        int result = sum == 0 ? 1 : 0;
        return result + countPath(root.left, sum) + countPath(root.right, sum);
    }

    public static TreeNode createBinaryTree(LinkedList<Integer> inputList) {
        if (inputList == null || inputList.isEmpty()) {
            return null;
        }
        TreeNode node = null;
        Integer data = inputList.removeFirst();
        if (data != null) {
            node = new TreeNode(data);
            node.left = createBinaryTree(inputList);
            node.right = createBinaryTree(inputList);
        }
        return node;
    }

    public static void main(String[] args) {
        /*LinkedList<Integer> integers = new LinkedList<>(Arrays.asList(5, 4, 11, 7, null, null, 2, null, null, null, 8, 13, null, null, 4,
                5, null, null, 1));*/
        /*LinkedList<Integer> integers = new LinkedList<>(Arrays.asList(3, 2, 9, null, null, 10, null,
                null, 8, null, 4));*/
        LinkedList<Integer> integers = new LinkedList<>(Arrays.asList(6, 2, 0, null, null, 4, null, null, 8, 7, null, null, 9, null, null));
        TreeNode binaryTree = createBinaryTree(integers);

        System.out.println(pathSum(binaryTree, 8));
    }

}