LintCode 1098 · Path Sum IV (二叉树遍历好题)

这篇文章介绍了一种解决给定表示深度小于5的二叉树的三数字列表,计算从根到所有叶节点路径和的算法。通过遍历和递归,利用unordered_map存储节点值和代码,计算路径总和。
摘要由CSDN通过智能技术生成

1098 · Path Sum IV
Algorithms
Medium

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 tree with the depth smaller than 5, you need to return the sum of all paths from the root towards the leaves.

Example
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.

解法1: 遍历即可。注意把num分为code和value两部分。code又可以分为layer和pos两部分。

class Solution {
public:
    /**
     * @param nums: the list
     * @return: the sum of all paths from the root towards the leaves
     */
    int pathSumIV(vector<int> &nums) {
        int n = nums.size();
        for (auto num : nums) {
            int value = num % 10;
            int code = num / 10;
            um[code] = value;
        }
        helper(11, 0);
        return totalPathSum;
    }
private:
    unordered_map<int, int> um; //<code, value>, e.g, 113=><11, 3>
    int totalPathSum = 0;
    void helper(int code, int pathSum) {
        if (um.find(code) == um.end()) return;
        pathSum += um[code];
        int pos = code % 10;
        int layer = code / 10;

        int leftPos = pos * 2 - 1, leftCode = (layer + 1) * 10 + leftPos;
        int rightPos = pos * 2, rightCode = (layer + 1) * 10 + rightPos;

        if (um.find(leftCode) == um.end() && um.find(rightCode) == um.end()) { //叶子节点
            totalPathSum += pathSum;
            return;
        }
        helper(leftCode, pathSum);
        helper(rightCode, pathSum);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值