• LeetCode 666. Path Sum IV


    原题链接在这里:https://leetcode.com/problems/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.

    题解:

    每个数字的前两位就决定了node所在的level 和 position. 

    那么这个node的left child 所在位置是 level + 1, 2*position-1. right child 所在位置是 level + 1, 2*position.

    把所有node的位置都存起来, 当走到一个node, 它的left 和 right child 都没有记录的时候就说明走到了叶子节点, 此时记录的path sum可以累积到结果中.

    Time Complexity: O(n). n是tree 的node数目.

    Space: O(n).

    AC Java:

     1 class Solution {
     2     int sum = 0;
     3     
     4     public int pathSum(int[] nums) {
     5         if(nums == null || nums.length == 0){
     6             return sum;
     7         }
     8         
     9         HashMap<Integer, Integer> hm = new HashMap<>();
    10         for(int num : nums){
    11             hm.put(num / 10, num % 10);
    12         }
    13         
    14         dfs(nums[0] / 10, hm, 0);
    15         return sum;
    16     }
    17     
    18     private void dfs(int rootKey, Map<Integer, Integer> hm, int cur){
    19         if(!hm.containsKey(rootKey)){
    20             return;
    21         }
    22         
    23         cur += hm.get(rootKey);
    24         
    25         int level = rootKey / 10;
    26         int pos = rootKey % 10;
    27         int leftKey = (level + 1) * 10 + 2 * pos - 1;
    28         int rightKey = leftKey + 1;
    29         
    30         if(!hm.containsKey(leftKey) && !hm.containsKey(rightKey)){
    31             sum += cur;
    32             return;
    33         }
    34         
    35         dfs(leftKey, hm, cur);
    36         dfs(rightKey, hm, cur);
    37     }
    38 }

    类似Path Sum III.

  • 相关阅读:
    SQL中的max()函数用法
    C#多线程
    C#操作redis
    spring+mybatis 多数据库事务
    实战项目中 :一个业务对多个数据库操作的同步的处理办法(要么都成功,要么都失败)Threadlocal 数据库事务
    redis之数据操作详解
    C# 两个数组取交集/补集 Intersect()
    MySQL创建索引
    MySQL每日执行
    MySQL删除重复数据
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/8098371.html
Copyright © 2020-2023  润新知