zoukankan      html  css  js  c++  java
  • python二叉树的遍历,递归和非递归及相关其它

    # encoding=utf-8
    class node(object):
    def __init__(self,data,left=None,right=None):
    self.data = data
    self.left = left
    self.right = right

    tree = node('D',node('B',node('A'),node('C')),node('E',right=node('G',node('F'))))

    # 先序
    def front(tree):
    if tree == None:
    return
    print(tree.data)
    front(tree.left)
    front(tree.right)

    def front_not(tree):
    if tree == None:
    return
    stack = []
    node = tree
    while node or stack:
    while node:
    print(node.data)
    stack.append(node)
    node = node.left
    node = stack.pop()
    node = node.right

    # 中序遍历
    def mid(tree):
    if tree == None:
    return
    mid(tree.left)
    print(tree.data)
    mid(tree.right)

    def mid_not(tree):
    if tree == None:
    return
    stack = []
    node = tree
    while node or stack:
    while node:
    stack.append(node)
    node = node.left
    node = stack.pop()
    print(node.data)
    node = node.right

    # 后序遍历
    def post(tree):
    if tree == None:
    return
    post(tree.left)
    post(tree.right)
    print(tree.data)

    def post_not(tree):
    if tree == None:
    return
    stack1 = []
    stack2 = []
    node = tree
    stack1.append(node)
    while stack1:
    node = stack1.pop()
    if node.left:
    stack1.append(node.left)
    if node.right:
    stack1.append(node.right)
    stack2.append(node)
    while stack2:
    print(stack2.pop().data)

    # 队列
    def leval(tree):
    if tree == None:
    return
    queue = []
    node = tree
    queue.append(node)
    while queue:
    node = queue.pop(0)
    print(node.data)
    if node.left:
    queue.append(node.left)
    if node.right:
    queue.append(node.right)
    # deep二叉树深度
    def deepth(tree):
    if tree == None:
    return 0
    left = deepth(tree.left)
    right = deepth(tree.right)
    return max(left,right)+1

    # print(deepth(tree))

    # 节点数
    def jiedian(tree):
    if tree == None:
    return 0
    return jiedian(tree.left)+jiedian(tree.right)+1

    # print(jiedian(tree))

    # 叶子节点
    def leaf(tree):
    if tree == None:
    return 0
    if tree.left == None and tree.right == None:
    return 1
    return leaf(tree.left)+leaf(tree.right)
    print(leaf(tree))


  • 相关阅读:
    软件设计——继承、多态、绑定、重置、创建型设计模式、结构型设计模式和行为设计模式
    软件设计——2017年下半年选择题重要知识点
    day---06 文件的操作
    day---05 基本数据类型(下)
    day---04 基本数据类型(上)
    day---04 流程控制
    day---03 基础的数据类型
    day---02 编程语言的发展史
    day---01 计算机基础
    Day——07
  • 原文地址:https://www.cnblogs.com/dreamyu/p/8276495.html
Copyright © 2011-2022 走看看