zoukankan      html  css  js  c++  java
  • 666. Path Sum IV

    If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digits integers.

    For each integer in this list:

    1. The hundreds digit represents the depth D of this node, 1 <= D <= 4.
    2. The tens digit represents the position P of this node in the level it belongs to, 1 <= P <= 8. The position is the same as that in a full binary tree.
    3. The units digit represents the value V of this node, 0 <= V <= 9.

    Given a list of ascending three-digits integers representing a binary with the depth smaller than 5. You need to return the sum of all paths from the root towards the leaves.

    Example 1:

    Input: [113, 215, 221]
    Output: 12
    Explanation: 
    The tree that the list represents is:
        3
       / 
      5   1
    
    The path sum is (3 + 5) + (3 + 1) = 12.
    

    Example 2:

    Input: [113, 221]
    Output: 4
    Explanation: 
    The tree that the list represents is: 
        3
         
          1
    
    The path sum is (3 + 1) = 4.

    先转换为树,可以用hashmap表示树,ref: https://leetcode.com/problems/path-sum-iv/discuss/106892/Java-solution-Represent-tree-using-HashMap

    time: O(n), space: O(n)

    class Solution {
        int sum = 0;
        Map<Integer, Integer> tree;
        
        public int pathSum(int[] nums) {
            if(nums == null || nums.length == 0) {
                return 0;
            }
            tree = new HashMap<>();
            for(int n : nums) {
                int k = n / 10;
                int v = n % 10;
                tree.put(k, v);
            }
            
            dfs(nums[0] / 10, 0);
            return sum;
        }
        
        public void dfs(int root, int preSum) {
            int depth = root / 10;
            int pos = root % 10;
            
            int left = (depth + 1) * 10 + pos * 2 - 1;
            int right = (depth + 1) * 10 + pos * 2;
            
            int curSum = preSum + tree.get(root);
            
            if(!tree.containsKey(left) && !tree.containsKey(right)) {
                sum += curSum;
                return;
            }
            if(tree.containsKey(left)) {
                dfs(left, curSum);
            }
            if(tree.containsKey(right)) {
                dfs(right, curSum);
            }
        }
    }
  • 相关阅读:
    数据库四种事务隔离级别
    JAVA自定义查询策略
    JAVA分页工具类
    Git常用指令
    TDH-大数据基础
    TDH-ssh免密登录
    TDH-search汇报理解
    TDH-常见运维指令
    pyecharts 0.5 visualmap 显示精度precision到小数
    14-influence 图机器学习之网络的影响力最大化
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10198868.html
Copyright © 2011-2022 走看看