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 >= || !flag[level * + pos])return ;//结点不存在
pathsum += mp[level * + pos];//当前路径和
if (!flag[(level + ) * + pos * ] && !flag[(level + ) * + pos * - ])ret += pathsum ;//到了叶节点 getsum(level+,pos*-,mp,flag,pathsum,ret);
getsum(level+,pos*,mp,flag,pathsum,ret);
}
int pathSum(vector<int>& nums)
{
map<int, int>mp;
map<int, bool>flag;
int ret=;
if (nums.size() == ) return ;
if (nums.size() == )return nums[] % ; for (auto n : nums){ mp[n / ] = n % ; flag[n / ] = true; } getsum(, , mp, flag, , ret);
return ret;
}

最新文章

  1. java核心技术第一卷
  2. 奥迪--Q5
  3. MVC中用Jpaginate分页 So easy!(兼容ie家族)
  4. Redis 配置文件 redis.conf 项目详解
  5. [HeadFirst-JSPServlet学习笔记][第三章:实战MVC]
  6. 关于各种排列(dfs)
  7. 二十二、oracle pl/sql分类二 函数
  8. Spring DM所提供的Bundle监听接口OsgiBundleApplicationContextListener
  9. 【adb】连接BlueStacks
  10. 机器学习技法:10 Random Forest
  11. 用Python开发小学二年级口算自动出题程序
  12. Spring Boot重定向的使用方法
  13. 《Swell数学》用户故事
  14. C#.NET 大型通用信息化系统集成快速开发平台 4.1 版本 - 访问记录功能改进
  15. iView 的分页结合表格用法
  16. django 路由分发
  17. LeetCode——727.Minimum Window Subsequence
  18. T-SQL 类型转换
  19. WiX: uninstall older version of the application
  20. zzuli 1430 多少个0

热门文章

  1. grid 布局的使用
  2. 一个 Safari 的 new Date() bug
  3. IIS网站的应用程序与虚拟目录的区别及应用
  4. 使用WIn10自带的Linux子系统
  5. SkipList 之详细分析
  6. Python学习:7.文件操作
  7. C程序设计语言笔记-第一章
  8. BZOJ1924_所驼门王的宝藏_KEY
  9. 长沙Uber优步司机奖励政策(1月4日~1月10日)
  10. Myeclipse - 问题集 - specified vm install not found