您好,欢迎来到暴趣科技网。
搜索
您的当前位置:首页leetcode — path-sum

leetcode — path-sum

来源:暴趣科技网
/**
 * Source : https://oj.leetcode.com/problems/path-sum/
 *
 *
 * Given a binary tree and a sum, determine if the tree has a root-to-leaf path
 * such that adding up all the values along the path equals the given sum.
 *
 * For example:
 * Given the below binary tree and sum = 22,
 *
 *               5
 *              / \
 *             4   8
 *            /   / \
 *           11  13  4
 *          /  \      \
 *         7    2      1
 *
 * return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
 */
public class PathSum {

    public boolean exists (TreeNode root, int target) {
        return hasSum(root, target, 0);
    }

    public boolean hasSum (TreeNode root, int target, int sum) {
        if (root == null) {
            if (target == sum) {
                return true;
            }
            return false;
        }
        boolean result = hasSum(root.leftChild, target, sum + root.value);
        if (result) {
            return true;
        }
        result = hasSum(root.rightChild, target, sum + root.value);
        if (result) {
            return true;
        }
        return false;
    }


    public TreeNode createTree (char[] treeArr) {
        TreeNode[] tree = new TreeNode[treeArr.length];
        for (int i = 0; i < treeArr.length; i++) {
            if (treeArr[i] == '#') {
                tree[i] = null;
                continue;
            }
            tree[i] = new TreeNode(treeArr[i]-'0');
        }
        int pos = 0;
        for (int i = 0; i < treeArr.length && pos < treeArr.length-1; i++) {
            if (tree[i] != null) {
                tree[i].leftChild = tree[++pos];
                if (pos < treeArr.length-1) {
                    tree[i].rightChild = tree[++pos];
                }
            }
        }
        return tree[0];
    }


    private class TreeNode {
        TreeNode leftChild;
        TreeNode rightChild;
        int value;

        public TreeNode(int value) {
            this.value = value;
        }

        public TreeNode() {

        }
    }

    public static void main(String[] args) {
        PathSum pathSum = new PathSum();
        char[] arr0 = new char[]{'#'};
        char[] arr1 = new char[]{'3','9','2','#','#','1','7'};
        char[] arr2 = new char[]{'3','9','2','1','6','1','7','5'};

        System.out.println(pathSum.exists(pathSum.createTree(arr0), 0));
        System.out.println(pathSum.exists(pathSum.createTree(arr1), 5));
        System.out.println(pathSum.exists(pathSum.createTree(arr2), 13));
    }

}

转载于:https://www.cnblogs.com/sunshine-2015/p/7823318.html

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baoquwan.com 版权所有 湘ICP备2024080961号-7

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务