zoukankan      html  css  js  c++  java
  • Python算法-二叉树深度优先遍历

    二叉树

    组成:

    1、根节点  BinaryTreeroot

    2、每一个节点,都有左子节点和右子节点(可以为空)  TreeNodevalueleftright

    二叉树的遍历:

    遍历二叉树:深度优先遍历、广度优先遍历。

     

    广度:先遍历兄弟节点,再遍历子节点    

    深度:先遍历子节点,再遍历兄弟节点

    上图深度遍历结果:50/20/60/15/30/70

    上图广度遍历结果:50/20/15/30/60/70

    深度遍历又分为先序、中序、后序的遍历方式:

    先序遍历:先根节点,再左子树,再右子树

    上图先序遍历结果:50/20/ 15/ 30/ 60/ 70

    中序遍历:先左子树,再根节点,再右子树

    上图中序遍历结果:15/20/30/50/60/70

    后序遍历:先左子树,再右子树,再根节点

    上图后序遍历结果:15/30/20/70/60/50

    代码实现:

    # encoding=utf-8

    class TreeNode(object): #定义二叉树类

        def __init__(self,val,left=None,right=None):

            self.val = val

            self.left = left

            self.right = right

    class BinaryTree(object):

        def __init__(self,root=None):

            self.root = root

        def preScan(self,retList, node): #先序遍历:先跟、再左、后右

            if node != None:

                retList.append(node.val)

                self.preScan(retList, node.left)

                self.preScan(retList, node.right)

            return retList

        def midScan(self, retList, node): #中序遍历:先左、再跟、后右

            if node != None:

                self.midScan(retList, node.left)

                retList.append(node.val)

                self.midScan(retList, node.right)

            return retList

        def postScan(self, retList, node): #后序遍历:先左、再右、后跟

            if node != None:

                self.postScan(retList, node.left)

                self.postScan(retList, node.right)

                retList.append(node.val)

            return retList

    if __name__ =='__main__':

        root = TreeNode(50)

        root.left = TreeNode(20,left=TreeNode(15),right=TreeNode(30,right=TreeNode(12)))

        root.right = TreeNode(60,right=TreeNode(70))

    bTree = BinaryTree(root)

    retList = bTree.preScan([],bTree.root)

    print retList

    retList2 = bTree.midScan([],bTree.root)

    print retList2

    retList3 = bTree.postScan([],bTree.root)

    print retList3

  • 相关阅读:
    vue绑定值与字符串拼接两种写法
    cmd 总是很卡,执行一条指令就卡死
    生产工具vscode
    js 关于 array 的相关操作––
    webAssembly
    github上fork别人的分支到目录下  
    68.Promise和setTimeout的区别
    67、Promise 构造函数是同步执行还是异步执行,那么 then 方法呢?
    66、深入理解 promise:promise的三种状态与链式调用
    65.ES6新的特性有哪些?
  • 原文地址:https://www.cnblogs.com/qingqing-919/p/8542501.html
Copyright © 2011-2022 走看看