python 生成满二叉树并进行深度优先搜索和宽度优先搜索

# -*- coding: UTF-8 -*-



from __future__ import print_function
deep = 3

#二叉树*******************************start

L = []
LW = []
class TreeNode(object):
    def __init__(self,data,left,right):
        self.data = data
        self.left = left
        self.right = right



def add_tree_node(tn,count=1):
    _deep = tn.data['deep']
    if  _deep < deep:
        #右子孙
        # print(_deep)
        temp = TreeNode({'deep':_deep+1,'node_num':count+1}, None, None)
        tn.right = temp
        print(tn.data['node_num'])
        count = add_tree_node(temp,count+1)
        #左子孙
        temp = TreeNode({'deep':_deep+1,'node_num':count+1},None,None)
        tn.left = temp
        print(tn.data['node_num'])
        count = add_tree_node(temp,count+1)
    return count

stack = []


def deep_travel_tree(tn):
    #读取当前节点并压入栈
    L.append(tn.data['node_num'])
    if tn.right != None:
        deep_travel_tree(tn.right)
    if tn.left != None:
        deep_travel_tree(tn.left)
    return


def width_travel_tree(tn):
    #压入节点
    LW.append(tn.data['node_num'])
    if tn.right != None and tn.left != None:
        stack.append(tn.right)
        stack.append(tn.left)
    if len(stack)!=0:
        temp = stack.pop(0)
        width_travel_tree(temp)
    return



def main():
    root =  TreeNode({'deep':1,'node_num':1},None,None)
    add_tree_node(root)
    deep_travel_tree(root)
    width_travel_tree(root)
    print(L)
    print(LW)

main()
    原文作者:满二叉树
    原文地址: https://blog.csdn.net/countofdane/article/details/78851677
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注