Path Sum with Digits Representation
If the depth of a tree is smaller than5
, then this tree can be represented by a list of three-digits integers.
Given a list ofascending
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:
Example 2:
Note
关键点是数位分离:
num / 10 is the index info with depth and pos: 10 * depth + pos,num % 10 is value of the node
left = 10 * (depth + 1) + 2 * pos - 1
right = 10 * (depth + 1) + 2 * pos
利用map存储: key is Index, val is value,dfs传入的是index信息,根据左右孩子的存在情况进行前序遍历,计算所有的路径和
时间空间都是O(N)
Code
Last updated