LeetCode Path Sum IV

本文介绍LeetCode上路径总和IV问题的解决思路及Java实现代码。该问题涉及三位数表示的二叉树,通过递归深度遍历的方式计算从根节点到叶节点的所有路径之和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里:https://leetcode.com/problems/path-sum-iv/description/

题目:

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 res;
 3     HashMap<Integer, Integer> hm;
 4     public int pathSum(int[] nums) {
 5         res = 0;
 6         hm = new HashMap<Integer, Integer>();
 7         for(int num : nums){
 8             hm.put(num/10, num%10);
 9         }
10         
11         dfs(nums[0]/10, 0);
12         return res;
13     }
14     
15     private void dfs(int node, int preSum){
16         if(!hm.containsKey(node)){
17             return;
18         }
19         
20         preSum += hm.get(node);
21         
22         int level = node/10;
23         int pos = node%10;
24         int left = (level+1)*10 + 2*pos - 1;
25         int right = left + 1;
26         if(!hm.containsKey(left) && !hm.containsKey(right)){
27             res += preSum;
28         }else{
29             dfs(left, preSum);
30             dfs(right, preSum);
31         }
32     }
33 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/8098371.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值