1104. Path In Zigzag Labelled Binary Tree

2019/10/14 Leetcode

1104. Path In Zigzag Labelled Binary Tree

Tags: ‘Math’, ‘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.

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:

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

Example 2:

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

 

Constraints:

  • 1 <= label <= 10^6

Solution

// Draw the graph
// For normal graph, keep dividing label by 2 till 1 will get the sequence
// For zigzag graph, each divide will give you the mirror node of previous level
class Solution {
    public List<Integer> pathInZigZagTree(int label) {
        LinkedList<Integer> result = new LinkedList<>();
        while(label > 0) {
            result.addFirst(label);
            label = findReverseNode(label/2);
        }
        return result;
    }
    
    private int findReverseNode(int n) {
        int i = 1;
        int level = 0;
        while (i <= n) {
            i = i<<1;
            level++;
        }
        return (1<<level) - 1 + (1<<(level-1)) - n;
    }
}

Search

    Table of Contents