[leetcode-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:
- The hundreds digit represents the depth Dof this node,1 <= D <= 4.
- The tens digit represents the position Pof this node in the level it belongs to,1 <= P <= 8. The position is the same as that in a full binary tree.
- The units digit represents the value Vof 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.
思路:
用一个map -- flag记录二叉树是否到了叶节点。用另一个map记录树节点所在位置和对应的值。
先序遍历二叉树,如果到了根节点,将当前路径和pathsum加到返回值总的和ret中。
遍历左子树。
遍历右子树。
void getsum(int level, int pos, map<int, int>& mp, map<int, bool>& flag, int pathsum, int& ret) { if (level >= 5 || !flag[level * 10 + pos])return ;//结点不存在 pathsum += mp[level * 10 + pos];//当前路径和 if (!flag[(level + 1) * 10 + pos * 2] && !flag[(level + 1) * 10 + pos * 2 - 1])ret += pathsum ;//到了叶节点 getsum(level+1,pos*2-1,mp,flag,pathsum,ret); getsum(level+1,pos*2,mp,flag,pathsum,ret); } int pathSum(vector<int>& nums) { map<int, int>mp; map<int, bool>flag; int ret=0; if (nums.size() == 0) return 0; if (nums.size() == 1)return nums[0] % 10; for (auto n : nums){ mp[n / 10] = n % 10; flag[n / 10] = true; } getsum(1, 1, mp, flag, 0, ret); return ret; }
 
                    
                     
                    
                 
                    
                

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号