从python中的给定数据生成二叉树 [英] generating a binary tree from given data in python

查看:290
本文介绍了从python中的给定数据生成二叉树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何将列表中的值读入二叉树中. 我有一个像这样的三角形:

         0
       1   2
     3   4   5
   6   7   8   9

我已经写了一个这样的类节点

class node:
    def __init__(self,data,left=None,right=None):
        self.data=data
        self.left=left
        self.right=right

基本上我想做的就是这样

node(0,node(1),node(2))

我想做一个可以处理更大三角形的递归函数.能以某种方式告诉我我该怎么办吗?

很明显,二叉树不是解决此问题的方法.我基本上想找出的是从上到下的所有不同组合.像0,1,3,6 0,2,5,8等

解决方案

这听起来像是功课,所以我不会写代码,但是这里有一些提示:

  1. 即使将三角形写为列表,也可以这样做,例如 0 1 2 3 4 5 6 7 8 9

  2. 因为这似乎是一棵完整的二叉树(假设您的三角形是错误的,并且第三行实际上应该是3 4 5 6),则您可以维护一个parents队列,其头是下一个父级需要孩子.请注意,我特别不建议递归.

完整的二叉树是其中每个非叶子节点恰好有两个子节点的树.如果这不应该是完整的二叉树,那么就没有确定的方式来解释问题(因为给定您的图片,节点1和2可能有1或2个子节点).

i wanted to know how to read values from a list into a binary tree. i have a triangle like this:

         0
       1   2
     3   4   5
   6   7   8   9

i have written a class node like this

class node:
    def __init__(self,data,left=None,right=None):
        self.data=data
        self.left=left
        self.right=right

basically what i want to do is something like this

node(0,node(1),node(2))

i want to make a recursive function that can handle much bigger triangles. Can somehow tell me what i am supposed to do?

edit: quite clearly binary tree is not the way to approach this problem. what i basically want to find out are all the different combination's from top to bottom. like 0,1,3,6 0,2,5,8 etc.

解决方案

This does sound like homework, so I won't write code, but here are a couple of hints:

  1. This could be done even if your triangle were written as a list, like 0 1 2 3 4 5 6 7 8 9

  2. Because it seems like this is a full binary tree (assuming your triangle is wrong and the third row is actually supposed to be 3 4 5 6), you could maintain a parents queue whose head is the next parent that needs children. Note that I am specifically not recommending recursion.

A full binary tree is one where each non-leaf node has exactly two children. If this is not supposed to be a full binary tree, then there is no deterministic way to interpret the problem (since each of node 1 and 2 could have 1 or 2 children, given your picture).

这篇关于从python中的给定数据生成二叉树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆