douza19870617 2018-09-07 10:19
浏览 38

二叉树标签的最大差异

I have the below question, but I'm having a hard time making sense of it and implementing it in PHP.

You have a binary tree with N nodes (1 <= N <= 100000) numbered from 0 to N - 1, each one labeled with some integer. You have to answer Q (1 <= Q <= 75000) queries, each one denoted by some node (some integer between 0 and N – 1).

The answer for each query is the largest difference between the labels you find in the path from the given node to the root of the tree, which will always be node 0. N will be given in the first line of the input. N lines follow the i-th line describes the data of the i-th node of the tree (the first line describes node 0, and so on), with 3 integers: label, left child, right child. The absence of any of the children will be denoted by -1. Then a line with the integer Q, followed by Q lines, each one a single query as described above.

Case 1:

For the input provided as follows:

3

10 1 2

12 -1 -1

15 -1 -1

2

1

2

The output of the program will be:

2

5

Case 2:

For the input provided as follows:

3

10 1 -1

15 2 -1

20 -1 -1

2

1

2

The output of the program will be:

5

10

Getting that maximum difference, for example for case 2,

I'd say output for query two would be 5 because from the data my binary tree has 10(root), then node 15 to the left of the root, then node 20 to the left of 15, so 20-15 is same as 15-10, which makes them both 5. Am I not understanding something here or what ... Any insights are welcome.

  • 写回答

1条回答 默认 最新

  • dongshao1021 2018-09-07 12:38
    关注

    Take into considerations all nodes between root and given node

    For the input provided as follows:

    3

    10 1 -1

    15 2 -1

    20 -1 -1

    1

    2

    The output of the program will be:

    10

    you get path 10-15-20 you should go with

    max(10,15,20) - min(10,15,20) => 10
    

    For the input provided as follows:

    7

    33 1 5

    11 2 -1

    27 3 6

    87 4 -1

    3 -1 -1

    666 -1 -1

    6666 -1 -1

    1

    4

    The output of the program will be:

    84

    you get longer chain 33-11-27-87-3 you get

    max(33,11,27,87,3) - min(33,11,27,87,3) => 87-3 => 84
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决