简体   繁体   English

为什么给定的二叉树用空节点构造?

[英]Why is the given binary tree constructed with empty node?

I have started to read about the trees structures and binary tree comes the first. 我已经开始阅读有关树的结构的知识,而二叉树是第一个。

I use the following resource: https://runestone.academy/runestone/static/pythonds/Trees/ListofListsRepresentation.html 我使用以下资源: https : //runestone.academy/runestone/static/pythonds/Trees/ListofListsRepresentation.html

There you can find the binary tree image: 在那里您可以找到二叉树图像:

在此处输入图片说明

With the list of list representation it looks like: 使用列表表示形式的列表,它看起来像:

在此处输入图片说明

And my questions are : why do we need the empty node marked with arrow, if it is not displayed on the binary tree image? 我的问题是 :如果二叉树图像上未显示箭头,为什么我们需要用箭头标记的空节点? As we know the binary tree can have up to two nodes, so, why do we need this empty node? 我们知道二叉树最多可以有两个节点,那么,为什么我们需要这个空节点? How does this empty node help us? 空节点如何帮助我们? Or it's just the convention which we should use? 还是我们应该使用的约定?

This is mostly explained in the link, specifically with the constructor function: 大部分在链接中对此进行了说明,特别是使用构造函数:

def BinaryTree(r):
  return [r, [], []]

When a new leaf is created, it always contains: 创建新叶子时,它始终包含:

  • The value itself 价值本身
  • The left node 左节点
  • The right node 正确的节点

This has the advantage that when you parse the tree, you do not have to check if left and right exist, as they always exist. 这样做的好处是,当你解析树,你没有检查leftright的存在,因为他们总是存在的。 This makes the code more regular and simple. 这使代码更加规则和简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM