腾讯暑期实习笔试笔记

腾讯暑期实习笔试笔记

题目:现存在一棵满二叉树,第一行为1,第二行为2 、3,第三行为4、5、6、7等等。以此类推,现要求输入n行,每行包含两个数x, k 求x在该二叉树下第k行的祖先节点,并打印出祖先节点。若该行没有祖先结点,则输出-1;
eg:
输入为:
4
10 1
10 2
10 3
10 4
输出:
1
2
5
-1
实现代码如下:

using System;
using System.Collections.Generic;
using System.Linq; 

class Program
{
    static void Main(string[] args)
    {        
        string line;
        Dictionary<int, List<int>> result = new Dictionary<int, List<int>>();
        List<int> results = new List<int>();
        while ((line = Console.ReadLine()) != null)
        {
            int n = int.Parse(line);
            HashSet<int> info = new HashSet<int>();
            for (int i = 0; i < n; i++)
            {
                line = Console.ReadLine();
                List<int> lineInfo = line.Split(' ').ToList().Select(t => int.Parse(t)).ToList();
                List<int> value = new List<int>();
                if(result.TryGetValue(lineInfo[0], out value))
                {
                    if (value.Count - lineInfo[1] >= 0)
                        results.Add(value[ value.Count - lineInfo[1]]);
                    else
                        results.Add(-1);
                }
                else
                {
                    List<int> value1 = new List<int>();
                    int u = lineInfo[0];
                    while(u /2 != 0)
                    {
                        value1.Add(u / 2);
                        u = u / 2;
                        
                    }
                    result.Add(lineInfo[0], value1);
                    results.Add(value1[value1.Count - lineInfo[1]]);
                }
            }
            foreach (var i in results)
                Console.WriteLine(i);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值