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