LeetCode - Medium - 1104. Path In Zigzag Labelled Binary Tree

港控/mmm° 2022-10-11 15:00 252阅读 0赞

Topic

  • Math
  • Binary Tree

Description

https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/

In an infinite binary tree where every node has two children, the nodes are labelled in row order.

In the odd numbered rows (ie., the first, third, fifth,…), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,…), the labelling is right to left.

a041964f6316c6e013fe6e908462ebf7.png

Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label.

Example 1:

  1. Input: label = 14
  2. Output: [1,3,4,14]

Example 2:

  1. Input: label = 26
  2. Output: [1,2,6,10,26]

Constraints:

  • 1 < = l a b e l < = 1 0 6 1 <= label <= 10^6 1<=label<=106

Analysis

The tree in problem reminds me of binary number representation.

Let’s use label 26 for example.
26 = 0b11010

If the tree is a normal full complete binary tree, the label 26 ‘s parent label should be :
26 >> 1 = 0b1101 = 13

But the correct label is 10 because of Zigzag.
10 = 0b1010

If you try 10 + 13:
10 + 13 = 23 = 0b10111

And the label 26 ‘s level minimum label is 16, maximum label is 31。
16 = 0b10000
31 = 0b11111

And (16 + 31) >> 1 = 23 = 10 + 13。 What a happy accident!
(16 + 31) >> 1 = 0b101111 >> 1 = 0b10111 = 23

So, we can use this formula to get the label 26 ‘s parent label:
(minimum + maximum) >> 1 - current >>1 = (16 + 31) >> 1 - 26 >> 1 = 10

Enjoy code!

Submission

  1. import java.util.LinkedList;
  2. import java.util.List;
  3. public class PathInZigzagLabelledBinaryTree {
  4. public List<Integer> pathInZigZagTree(int label) {
  5. List<Integer> result = new LinkedList<>();
  6. while(label > 0) {
  7. result.add(0, label);
  8. if(label == 1) break;
  9. int min = 1;
  10. for(int i = 1; (label >>> i) > 0; i++)
  11. min <<= 1;
  12. label = ((min + (min << 1) - 1) >> 1) - (label >> 1);
  13. }
  14. return result;
  15. }
  16. }

Test

  1. import static org.junit.Assert.*;
  2. import org.hamcrest.collection.IsIterableContainingInOrder;
  3. import org.junit.Test;
  4. public class PathInZigzagLabelledBinaryTreeTest {
  5. @Test
  6. public void test() {
  7. PathInZigzagLabelledBinaryTree pObj = new PathInZigzagLabelledBinaryTree();
  8. assertThat(pObj.pathInZigZagTree(26), IsIterableContainingInOrder.contains(1,2,6,10,26));
  9. assertThat(pObj.pathInZigZagTree(14), IsIterableContainingInOrder.contains(1,3,4,14));
  10. }
  11. }

发表评论

表情:
评论列表 (有 0 条评论,252人围观)

还没有评论,来说两句吧...

相关阅读