美文网首页
Binary Tree Path Sum IV

Binary Tree Path Sum IV

作者: Frank_Kivi | 来源:发表于2018-06-26 20:29 被阅读3次

https://www.lintcode.com/problem/binary-tree-path-sum-iv/description

import java.util.Arrays;

public class Solution {
    private int max = 0;
    /**
     * @param nums: a list of integers
     * @return: return an integer
     */
    public int pathSum(int[] nums) {
        // write your code here
        int[] dp = new int[20];
        Arrays.fill(dp, -1);
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            int hundred = num / 100;
            int ten = (num % 100) / 10;
            int left = num % 10;
            int offset = getOffset(hundred);
            dp[offset + ten - 1] = left;
        }
        treeWalk(dp, 0, 0);
        return max;
    }

    private void treeWalk(int[] dp, int i, int sum) {
        int left = 2 * i + 1;
        int count = 0;
        int sum1 = sum + dp[i];
        if (left < dp.length && dp[left] != -1) {
            treeWalk(dp, 2 * i + 1, sum1);
            count++;
        }
        int right = 2 * i + 2;
        if (right < dp.length && dp[right] != -1) {
            treeWalk(dp, 2 * i + 2, sum1);
            count++;
        }
        if (count == 0) {
            max += sum1;
        }
    }

    private int getOffset(int hundred) {
        int result = 0;
        for (int i = 0; i < hundred - 1; i++) {
            result += Math.pow(2, i);
        }
        return result;
    }
}

相关文章

网友评论

      本文标题:Binary Tree Path Sum IV

      本文链接:https://www.haomeiwen.com/subject/mkzmyftx.html