简体   繁体   English

从预遍历列表Python构造完整的二叉树

[英]Construct complete binary tree from preorder traversal list Python

How do I construct a binary tree (not binary search tree) from a preorder listing in Python using only the built in list? 如何仅使用内置列表从Python中的预购列表构造二叉树(不是二叉搜索树)? Each node in the preorder listing also has a "flag" that shows if it's a leaf or internal node. 预购清单中的每个节点都有一个“标志”,显示它是叶节点还是内部节点。 And each node has 2 children (No 0 or 1 child) 每个节点有2个子节点(没有0或1个子节点)

I made a class to represent a Node 我做了一个类来代表一个节点

class Node:
    def __init__(self, initType):
        self.type = initType
        self.leftChild = None
        self.rightChild = None

I think I should use a stack here, but I don't want to import the stack library. 我想我应该在这里使用stack ,但是我不想import stack库。

Solutions I found online are for BST only or the input consists of an inorder list and a preorder list, not just the preorder list alone. 我在网上找到的解决方案仅适用于BST,或者输入内容包含订单列表和预购列表,而不仅仅是单独的预购列表。

You can not uniquely re-create a binary tree given only the pre order traversal. 仅给定遍历遍历,就不能唯一地重新创建二叉树。 That is why the solutions you found online were for a BST or also provided the in order list as well. 因此,您在网上找到的解决方案是针对BST的,或者还提供了订购清单。

For example, if the pre order list was gives as [1, 2, 3] 例如,如果预购清单的给定为[1、2、3]

then your original binary tree could be: 那么您原始的二叉树可能是:

         1
       /
     2
   /
  3

or it could be: 或者可能是:

1
  \
   2
    \
     3 

** notice how they are different trees but would have the same pre order traversal lists! **注意它们是如何不同的树,但是会有相同的预遍历列表!

If this question was asked in an interview, it was meant to see if you would notice the fact that a unique binary tree could not be implemented and have you clarify the question: "Is the binary tree a binary search tree?" 如果在面试中提出了这个问题,则意味着您是否会注意到无法实现唯一的二叉树这一事实,并且您是否想出一个问题:“二叉树是否为二叉搜索树?”

It is very common in interviews to leave out facts from a question to have you ask questions. 在面试中很常见的是遗漏问题的事实,让您问问题。

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

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