二叉树
Posted 月色真美丶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树相关的知识,希望对你有一定的参考价值。
二叉树是由n个节点构成,它有可能是空树,也有可能是非空树。
对于非空树,有且仅有一个根节点,和左右两个不相交的左子树和右子树
左子树和右子树有左右之分,不可颠倒
二叉树的遍历法;
1.深度优先法
前序遍历,访问根节点,遍历左子树,再遍历右子树
中序遍历,遍历左子树,访问根节点,再遍历右子树
后序遍历,遍历左子树,遍历右子树,再访问根节点
2.广度优先法
层级遍历,从根节点开始一层一层的自左向右遍历节点
代码实现:
# -*- coding = utf-8 -*- # @Author: Wchime # @time: 2023/1/23 14:09 # @file: 二叉树.py class Node(object): """ 树节点,包含值和左右子节点 """ def __init__(self, item): self.item = item self.lchild = None self.rchild = None class Tree(object): """ 二叉树 """ def __init__(self): self.__root = None def is_empty(self): """ 判断树是否为空 :return: """ return self.__root is None def append(self, item): """ 添加节点 :param item: :return: """ node = Node(item) if self.is_empty(): self.__root = node return else: li = [self.__root] while li: cur = li.pop(0) if cur.lchild is None: cur.lchild = node return else: li.append(cur.lchild) if cur.rchild is None: cur.rchild = node return else: li.append(cur.rchild) def travel_preorder(self): """ 先序遍历 :return: """ def recur(node): """ 递归 :return: """ if node is None: # print(\'None\') return print(node.item, end=" ") recur(node.lchild) recur(node.rchild) recur(self.__root) print(\'\\n\') def travel_inorder(self): """ 中序遍历 :return: """ def recur(node): """ 递归 :return: """ if node is None: # print(\'None\') return recur(node.lchild) print(node.item, end=" ") recur(node.rchild) recur(self.__root) print(\'\\n\') def travel_postorder(self): def recur(node): """ 递归 :return: """ if node is None: # print(\'None\') return recur(node.lchild) recur(node.rchild) print(node.item, end=" ") recur(self.__root) print(\'\\n\') def travel_breadth(self): """ 广度优先遍历 :return: """ if self.__root is None: return li = [self.__root] while li: cur = li.pop(0) print(cur.item, end=" ") if cur.lchild is not None: li.append(cur.lchild) if cur.rchild is not None: li.append(cur.rchild) print(\'\\n\') if __name__ == "__main__": tree = Tree() print(tree.is_empty()) tree.append(3) tree.append(7) tree.append(9) tree.append(5) tree.append(2) tree.append(1) tree.travel_preorder() tree.travel_inorder() tree.travel_postorder() tree.travel_breadth()
以上是关于二叉树的主要内容,如果未能解决你的问题,请参考以下文章
二叉树及特殊二叉树(满二叉树完全二叉树二叉排序树平衡二叉树)的定义和性质(附详细推理过程)