Path Sum IV

update Aug 31, 2017 0:02

LeetCodearrow-up-right

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:

  1. The hundreds digit represents the depthDof this node,1 <= D <= 4.

  2. The tens digit represents the positionPof 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 valueVof this node,0<= V<= 9.

Given a list ofascendingthree-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:

Basic Idea:

破题点就在于所给的信息其实相当于告诉了我们每个 node 在一个完全二叉树中的精确位置,一想到这种设定,我们马上自然想到了 heap,于是一种解法自然成型:利用heap保存二叉树的方法,通过所给数字中的位置信息直接计算出其在数组中的index。

具体实现的过程中,有两个思路: 1. 和heap的保存方法一样,使用一个数组,由于至多有四层,考虑到可能需要探测的孩子节点的index,我们可以使用一个 Integer[32](null 表示不存在); 2. 也可以使用一个 HashMap<Integer, Integer> 来存,key是index,这样就可用contains() 来判断孩子是否存在;

Java Code:

方法1,使用Integer[32]:

方法2, 使用 HashMap:

update Dec 21, 2017 1:26

Update

更新一个 python code,用 dict 实现 tree,居然在 python3 的答案中是最快的。

Python Code: