666 Path Sum IV
666. Path Sum IV
1. Question
If the depth of a tree is smaller than5
, 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
D
of this node,1 <= D <= 4.
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.
The units digit represents the value
V
of this node,0 <= V <= 9.
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:
2. Implementation
思路:这题给一个数组,数组的每个数是都是三位数,百位数代表在树的第几层,中位数代表数在该层的位置(从1开始算), 而个位数则代表该节点在树里的值。
(1) 题目提到,位置的信息是和full binary tree一样的,这意味着,给定一个node的位置,我们知道它的left children在下一层的位置是node的position * 2 -1(position是从1开始), right children的position则是node的position * 2。
(2)有了以上这些信息后,我们就可以利用一个map, 以数组每个数的前面两位作为key, 最后一位作为value, 放在map里,利用Path Sum同样的思路从根节点(数组第一个数)递归地找出path sum
3. Time & Space Complexity
时间空间复杂度都是O(n)
Last updated