1104 Path In Zigzag Labelled Binary Tree

29 篇文章 0 订阅
23 篇文章 0 订阅

1 题目

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]

2 尝试解

2.1 分析

一个无限大的完全二叉树,其值按Z字型从1依序递增1。给定一个值,问从根节点到该值所在节点的路径。

考虑同样的二叉树,但是值按照每层从左向右的顺序依序递增1。在此二叉树中,发现任意一个值为N的节点,其父节点的值为N/2。所以只需要重复取半,即可得到从该节点到根节点的路径。如给定14,路径为{14,7,3,1}。

              1                  1
             / \                / \
            3   2              2   3
           / \ / \            / \ / \
          4  5 6  7          4  5 6  7

现在考虑两棵二叉树之间的相互转化,给定值label及其所在的层数height(可由label求出),label'表示对应节点在另一棵二叉树中的值,有

height%2 == 0  label = label'

height%2 == 1 label+label' = 2^height + 2^(height-1) - 1

只需要对路径中的每个元素采用上述转化规则,即将一个路径转化为另一个对应路径。

2.2 代码

class Solution {
public:
    int transform(int label, int height){
        if(height % 2 == 1) return label;
        else return (1 << height) - label - 1 + (1 << (height-1));
    }
    vector<int> pathInZigZagTree(int label) {
        int height = 1;
        vector<int> result;
        while(label >= (1 << height)){
            height += 1;
        }
        label = transform(label,height);
        while(height > 0){
            result.push_back(transform(label,height));
            label /= 2;
            height--;
        }
        reverse(result.begin(),result.end());
        return result;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值