zoukankan      html  css  js  c++  java
  • 二叉树

    #coding=utf-8
    
    
    #构建二叉树(二叉树结点)
    class Node(object):
        def __init__(self, data, left=None, right=None):
            self.data = data
            self.left = left
            self.right = right
    
    tree = Node(1, Node(3, Node(7, Node(0)), Node(6)), Node(2, Node(5), Node(4)))
    
    
    #层次遍历
    def level_order(tree):
       if tree == None:
           return
       q = []
       q.append(tree)
       while q:
           current = q.pop(0)
           print(current.data)
           if current.left:
               q.append(current.left)
           if current.right:
               q.append(current.right)
    
    
    #按层次打印
    def level2_order(tree):
        if tree == None:
            return
        q = []
        q.append(tree)
        level = 0
        d = []
        result = {}
        next_level_num = 0
        current_level_num = 1
        while q:
            current = q.pop(0)
            current_level_num -= 1
            d.append(current.data)
            if current.left:
                q.append(current.left)
                next_level_num += 1
            if current.right:
                q.append(current.right)
                next_level_num += 1
            if current_level_num == 0:
                current_level_num = next_level_num
                next_level_num = 0
                result[level] = d
                level += 1
                d = []
        print(result)
    
    
    #深度遍历
    def deep(tree):
        if tree == None:
            return
        print(tree.data)
        deep(tree.left)
        deep(tree.right)
    
    
    #前序遍历(根 左 右)
    def pre_order(tree):
        if tree == None:
            return
        print(tree.data)
        if tree.left:
            pre_order(tree.left)
        if tree.right:
            pre_order(tree.right)
    
    
    #中序遍历(左 根 右)
    def mid_order(tree):
        if tree == None:
            return
        if tree.left:
            pre_order(tree.left)
        print(tree.data)
        if tree.right:
            pre_order(tree.right)
    
    
    #后序遍历( 左 右 根)
    def post_order(tree):
        if tree == None:
            return
        if tree.left:
            pre_order(tree.left)
        if tree.right:
            pre_order(tree.right)
        print(tree.data)
    当你的才华还撑不起你的野心时
    那你就应该静下心来学习
    当你的能力还驾驭不了你的目标时
    那就应该沉下心来历练
  • 相关阅读:
    pd_ds中的hash
    洛谷P1333 瑞瑞的木棍(欧拉回路)
    2-SAT速成
    洛谷P3209 [HNOI2010]PLANAR(2-SAT)
    BZOJ2199: [Usaco2011 Jan]奶牛议会(2-SAT)
    BZOJ 1823: [JSOI2010]满汉全席(2-SAT)
    IOS深入学习(1)之图标文件(icon files)
    控制反转思想的理解实例
    poj 3259 (Bellman_Ford判断负环)
    POJ 2686 Traveling by Stagecoach 壮压DP
  • 原文地址:https://www.cnblogs.com/yang-xiansen/p/9053150.html
Copyright © 2011-2022 走看看