码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode-666-Path Sum IV]

时间:2017-08-27 13:30:43      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:binary   val   ted   map   inpu   lag   output   遍历   leave   

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.

思路:

用一个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;
}

 

[leetcode-666-Path Sum IV]

标签:binary   val   ted   map   inpu   lag   output   遍历   leave   

原文地址:http://www.cnblogs.com/hellowooorld/p/7440103.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!