【LeetCode】1104. Path In Zigzag Labelled Binary Tree

15 篇文章 0 订阅

题目

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

题意

给定一个label,根据label生成二叉树,如上图所示,这颗二叉树是一颗满二叉树,深度是label所在深度,其中从上到下是节点值依次递增,偶数行节点逆序排列,奇数行节点顺序排列,要在这颗树种找到从根节点到label所在节点路径上的值。

代码

这个题的解法应该有很多,我的想法是想按每行节点都是顺序排列来找出这一条路径,然后找出路径上偶数行节点的对称节点,替换路径中该节点的值,具体代码如下:

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Integer> pathInZigZagTree(int label) {
        List<Integer> result = new ArrayList<>();
        int high = 0;
        int index = label;

		// 在全部为顺序排列的情况下找出路径
        while (index > 0){
            result.add(0,index);
            if (index % 2 != 0){
                index = (index - 1) / 2;
            }else {
                index = index / 2;
            }
        }

		// 为路径中奇数行的节点找对称节点
		// 当result节点数量(也就是树的深度)是偶数时,则reuslt偶数索引需要在树种找对称节点
        if (result.size() % 2 == 0) {
            for (int i = 2; i < result.size() - 1; i+=2) {
                if (i % 2 == 0){
                    int rowMax = (int) Math.pow(2,i + 1) - 1;
                    int rowMin = rowMax - (int)Math.pow(2,i) + 1;
                    result.set(i,rowMin + (rowMax - result.get(i)));
                }

            }
        // 当result节点数量(也就是树的深度)是奇数时,则reuslt奇数索引需要在树种找对称节点
        }else {
            for (int i = 1; i < result.size() - 1; i+=2) {
                if (i % 2 != 0){
                    int rowMax = (int) Math.pow(2,i + 1) - 1; // 当前行最大值
                    int rowMin = rowMax - (int)Math.pow(2,i) + 1; // 当前行最小值
                    result.set(i,rowMin + (rowMax - result.get(i))); // 节点和最大值的距离就是对称节点和最小值的距离,所以此处找出对称节点值
                }
            }
        }

        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WGeeker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值