Leetcode 666. Path Sum IV

666. Path Sum IV

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:
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 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:

Example 2:

Answer

In my view, this is a simple tree’s route problem, we can choose DFS or BFS to solve it. What’s the hard is that we should transfer Integer to a valid tree structs.

But , we can use a reserved BFS to solve the problem. And using a array int[] time to record visited times of each node.

Like the Example 1, now that two leaf nodes has no child node, they should be visited just once. And the root node has two leaves, so it should be visited twice.

In my code, I used (nums[j]/100==nums[i]/100-1)&&((nums[j])/10)%10==((nums[i]/10)%10+1)/2) to judge if current node has parent node.
– the former judges the layer of parent node and the latter judges if the it’s position.
the visited time of parent node is the sum of its both child node visited time, and finally we can add them together to get result.

Code is following:

Leave a Reply

Your email address will not be published. Required fields are marked *