资讯专栏INFORMATION COLUMN

Python实现二叉树相关算法

guyan0319 / 1277人阅读

摘要:节点定义二叉树定义先序遍历递归方式先序遍历,递归方式非递归方式先序遍历,非递归方式中序遍历递归方式中序遍历,递归方式非递归方式中序遍历,非递归方式后序遍历递归方式后序遍历,递归方式非递归方式后序遍历,非递归方式分层遍历分层遍历,使用队

节点定义

</>复制代码

  1. class Node(object):
  2. def __init__(self, left_child, right_child, value):
  3. self._left_child = left_child
  4. self._right_child = right_child
  5. self._value = value
  6. @property
  7. def left_child(self):
  8. return self._left_child
  9. @property
  10. def right_child(self):
  11. return self._right_child
  12. @left_child.setter
  13. def left_child(self, value):
  14. self._left_child = value
  15. @right_child.setter
  16. def right_child(self, value):
  17. self._right_child = value
  18. @property
  19. def value(self):
  20. return self._value
  21. @value.setter
  22. def value(self, value):
  23. self._value = value
二叉树定义

</>复制代码

  1. class Tree(object):
  2. def __init__(self, value):
  3. self._root = Node(None, None, value=value)
  4. @property
  5. def root(self):
  6. return self._root
先序遍历 递归方式

</>复制代码

  1. """
  2. 先序遍历,递归方式
  3. """
  4. def preoder(root):
  5. if not isinstance(root, Node):
  6. return None
  7. preorder_res = []
  8. if root:
  9. preorder_res.append(root.value)
  10. preorder_res += preoder(root.left_child)
  11. preorder_res += preoder(root.right_child)
  12. return preorder_res
非递归方式

</>复制代码

  1. """
  2. 先序遍历,非递归方式
  3. """
  4. def pre_order_not_recursion(root):
  5. if not isinstance(root, Node):
  6. return None
  7. stack = [root]
  8. result = []
  9. while stack:
  10. node = stack.pop(-1)
  11. if node:
  12. result.append(node.value)
  13. stack.append(node.right_child)
  14. stack.append(node.left_child)
  15. return result
中序遍历 递归方式

</>复制代码

  1. """
  2. 中序遍历,递归方式
  3. """
  4. def middle_order(root):
  5. if not isinstance(root, Node):
  6. return None
  7. middle_res = []
  8. if root:
  9. middle_res += middle_order(root.left_child)
  10. middle_res.append(root.value)
  11. middle_res += middle_order(root.right_child)
  12. return middle_res
非递归方式

</>复制代码

  1. """
  2. 中序遍历,非递归方式
  3. """
  4. def middle_order_bot_recursion(root):
  5. if not isinstance(root, Node):
  6. return None
  7. result = []
  8. stack = [root.right_child, root.value, root.left_child]
  9. while stack:
  10. temp = stack.pop(-1)
  11. if temp:
  12. if isinstance(temp, Node):
  13. stack.append(temp.right_child)
  14. stack.append(temp.value)
  15. stack.append(temp.left_child)
  16. else:
  17. result.append(temp)
  18. return result
后序遍历 递归方式

</>复制代码

  1. """
  2. 后序遍历,递归方式
  3. """
  4. def post_order(root):
  5. if not isinstance(root, Node):
  6. return None
  7. post_res = []
  8. if root:
  9. post_res += post_order(root.left_child)
  10. post_res += post_order(root.right_child)
  11. post_res.append(root.value)
  12. return post_res
非递归方式

</>复制代码

  1. """
  2. 后序遍历,非递归方式
  3. """
  4. def post_order_not_recursion(root):
  5. if not isinstance(root, Node):
  6. return None
  7. stack = [root.value, root.right_child, root.left_child]
  8. result = []
  9. while stack:
  10. temp_node = stack.pop(-1)
  11. if temp_node:
  12. if isinstance(temp_node, Node):
  13. stack.append(temp_node.value)
  14. stack.append(temp_node.right_child)
  15. stack.append(temp_node.left_child)
  16. else:
  17. result.append(temp_node)
  18. return result
分层遍历

</>复制代码

  1. """
  2. 分层遍历,使用队列实现
  3. """
  4. def layer_order(root):
  5. if not isinstance(root, Node):
  6. return None
  7. queue = [root.value, root.left_child, root.right_child]
  8. result = []
  9. while queue:
  10. temp = queue.pop(0)
  11. if temp:
  12. if isinstance(temp, Node):
  13. queue.append(temp.value)
  14. queue.append(temp.left_child)
  15. queue.append(temp.right_child)
  16. else:
  17. result.append(temp)
  18. return result
计算二叉树结点个数

</>复制代码

  1. """
  2. 计算二叉树结点个数,递归方式
  3. NodeCount(root) = NodeCount(root.left_child) + NodeCount(root.right_child)
  4. """
  5. def node_count(root):
  6. if root and not isinstance(root, Node):
  7. return None
  8. if root:
  9. return node_count(root.left_child) + node_count(root.right_child) + 1
  10. else:
  11. return 0
  12. """
  13. 计算二叉树结点个数,非递归方式
  14. 借用分层遍历计算
  15. """
  16. def node_count_not_recursion(root):
  17. if root and not isinstance(root, Node):
  18. return None
  19. return len(layer_order(root))
计算二叉树深度

</>复制代码

  1. """
  2. 计算二叉树深度,递归方式
  3. tree_deep(root) = 1 + max(tree_deep(root.left_child), tree_deep(root.right_child))
  4. """
  5. def tree_deep(root):
  6. if root and not isinstance(root, Node):
  7. return None
  8. if root:
  9. return 1 + max(tree_deep(root.left_child), tree_deep(root.right_child))
  10. else:
  11. return 0
  12. """
  13. 计算二叉树深度,非递归方法
  14. 同理参考分层遍历的思想
  15. """
  16. def tree_deep_not_recursion(root):
  17. if root and not isinstance(root, Node):
  18. return None
  19. result = 0
  20. queue = [(root, 1)]
  21. while queue:
  22. temp_node, temp_layer = queue.pop(0)
  23. if temp_node:
  24. queue.append((temp_node.left_child, temp_layer+1))
  25. queue.append((temp_node.right_child, temp_layer+1))
  26. result = temp_layer + 1
  27. return result-1
计算二叉树第k层节点个数

</>复制代码

  1. """
  2. 计算二叉树第k层节点个数,递归方式
  3. kth_node_count(root, k) = kth_node_count(root.left_count, k-1) + kth_node_count(root.right_count, k-1)
  4. """
  5. def kth_node_count(root, k):
  6. if root and not isinstance(root, Node):
  7. return None
  8. if not root or k <= 0:
  9. return 0
  10. if k == 1:
  11. return 1
  12. return kth_node_count(root.left_child, k-1) + kth_node_count(root.right_child, k-1)
  13. """
  14. 计算二叉树第K层节点个数,非递归方式
  15. """
  16. def kth_node_count_not_recursion(root, k):
  17. if root and not isinstance(root, Node):
  18. return None
  19. if not root or k <= 0:
  20. return 0
  21. if k == 1:
  22. return 1
  23. queue = [(root, 1)]
  24. result = 0
  25. while queue:
  26. temp_node, temp_layer = queue.pop(0)
  27. if temp_node:
  28. if temp_layer == k:
  29. result += 1
  30. elif temp_layer > k:
  31. return result
  32. else:
  33. queue.append((temp_node.left_child, temp_layer+1))
  34. queue.append((temp_node.right_child, temp_layer+1))
  35. return result
计算二叉树叶子节点个数

</>复制代码

  1. """
  2. 计算二叉树叶子节点个数,递归方式
  3. 关键点是叶子节点的判断标准,左右孩子皆为None
  4. """
  5. def leaf_count(root):
  6. if root and not isinstance(root, Node):
  7. return None
  8. if not root:
  9. return 0
  10. if not root.left_child and not root.right_child:
  11. return 1
  12. return leaf_count(root.left_child) + leaf_count(root.right_child)
判断两个二叉树是不是相同

</>复制代码

  1. """
  2. 判断两个二叉树是不是相同,递归方式
  3. isSame(root1, root2) = (root1.value == root2.value)
  4. and isSame(root1.left, root2.left)
  5. and isSame(root1.right, root2.right)
  6. """
  7. def is_same_tree(root1, root2):
  8. if not root1 and not root2:
  9. return True
  10. if root1 and root2:
  11. return (root1.value == root2.value) and
  12. is_same_tree(root1.left_child, root2.left_child) and
  13. is_same_tree(root1.right_child, root2.right_child)
  14. else:
  15. return False
判断是否为二分查找树BST

</>复制代码

  1. """
  2. 判断是否为二分查找树BST,递归方式
  3. 二分查找树的定义搞清楚,二分查找树的中序遍历结果为递增序列
  4. """
  5. def is_bst_tree(root):
  6. if root and not isinstance(root, Node):
  7. return None
  8. def is_asc(order):
  9. for i in range(len(order)-1):
  10. if order[i] > order[i+1]:
  11. return False
  12. return True
  13. return is_asc(middle_order_bot_recursion(root))
测试方法

</>复制代码

  1. if __name__ == "__main__":
  2. tree = Tree(1)
  3. tree1 = Tree(1)
  4. node6 = Node(None, None, 7)
  5. node5 = Node(None, None, 6)
  6. node4 = Node(None, None, 5)
  7. node3 = Node(None, None, 4)
  8. node2 = Node(node5, node6, 3)
  9. node1 = Node(node3, node4, 2)
  10. tree.root.left_child = node1
  11. tree.root.right_child = node2
  12. tree1.root.left_child = node2
  13. tree1.root.right_child = node2
  14. print(is_bst_tree(tree.root))

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/43252.html

相关文章

  • 树和树的算法

    摘要:树和树的算法一树树的概念树英语是一种抽象数据类型或是实作这种抽象数据类型的数据结构,用来模拟具有树状结构性质的数据集合。一种时间复杂度额外空间复杂度的二叉树的遍历方式,为二叉树的节点个数。 树和树的算法 一、树 1.1 树的概念 树(英语:tree)是一种抽象数据类型(ADT)或是实作这种抽象数据类型的数据结构,用来模拟具有树状结构性质的数据集合。它是由n(n>=1)个有限节点组成一个...

    RaoMeng 评论0 收藏0
  • 树和树的算法

    摘要:树和树的算法一树树的概念树英语是一种抽象数据类型或是实作这种抽象数据类型的数据结构,用来模拟具有树状结构性质的数据集合。一种时间复杂度额外空间复杂度的二叉树的遍历方式,为二叉树的节点个数。 树和树的算法 一、树 1.1 树的概念 树(英语:tree)是一种抽象数据类型(ADT)或是实作这种抽象数据类型的数据结构,用来模拟具有树状结构性质的数据集合。它是由n(n>=1)个有限节点组成一个...

    PiscesYE 评论0 收藏0
  • Python_数据结构与算法

    摘要:什么是数据结构数据的组织结构方式一组数据如何存储,基本数据类型,,的封装算法与数据结构的区别数据结构只是静态的描述了数据元素之间的关系。高效的程序需要在数据结构的基础上设计和选择算法。 数据结构和算法基础 什么是数据结构和算法:兵法,计算的方法。算法是独立存在的一种解决问题的方法和思想。 算法的特征: 输入:算法具有0个或多个输入 输出:算法至少有1个或多个输出 有穷性:算法在有限的...

    Kylin_Mountain 评论0 收藏0
  • Python数据结构——二叉堆的实现

    摘要:二叉堆的有趣之处在于,其逻辑结构上像二叉树,却是用非嵌套的列表来实现。二叉堆结构性质为了更好地实现堆,我们采用二叉树。图完全二叉树有意思的是我们用单个列表就能实现完全树。下列所示的代码是完全二叉堆的实现。 优先队列的二叉堆实现 在前面的章节里我们学习了先进先出(FIFO)的数据结构:队列(Queue)。队列有一种变体叫做优先队列(Priority Queue)。优先队列的出队(Dequ...

    stackfing 评论0 收藏0

发表评论

0条评论

guyan0319

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<