gpt4 book ai didi

Python实现二叉树的常见遍历操作总结【7种方法】

转载 作者:qq735679552 更新时间:2022-09-28 22:32:09 25 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章Python实现二叉树的常见遍历操作总结【7种方法】由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

本文实例讲述了Python实现二叉树的常见遍历操作。分享给大家供大家参考,具体如下:

二叉树的定义:

?
1
2
3
4
5
class TreeNode:
   def __init__( self , x):
     self .val = x
     self .left = None
     self .right = None

二叉树的前序遍历 。

递归 。

?
1
2
3
4
5
6
7
def preorder(root,res = []):
   if not root:
     return
   res.append(root.val)
   preorder(root.left,res)
   preorder(root.right,res)
   return res

迭代 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
def preorder(root):
   res = []
   if not root:
     return []
   stack = [root]
   while stack:
     node = stack.pop()
     res.append(node.val)
     if node.right:
       stack.append(node.right)
     if node.left:
       stack.append(node,left)
   return res

二叉树的中序遍历 。

递归 。

?
1
2
3
4
5
6
7
def inorder(root,res = []):
   if not root:
     return
   inorder(root.left,res)
   res.append(root.val)
   inorder(root.right,res)
   return res

迭代 。

?
1
2
3
4
5
6
7
8
9
10
11
12
def inorder(root):
   stack = []
   node = root
   res = []
   while stack or node:
     while node:
       stack.append(node)
       node = node.left
     node = stack.pop()
     res.append(node.val)
     node = node.right
   return res

二叉树的后序遍历 。

递归 。

?
1
2
3
4
5
6
7
def laorder(root,res = []):
   if not root:
     return
   laorder(root.left,res)
   laorder(root.right,res)
   res.append(root.val)
   return res

迭代 。

?
1
2
3
4
5
6
7
8
9
10
11
def laorder(root):
   stack = [root]
   res = []
   while stack:
     node = stack.pop()
     if node.left:
       stack.append(node.left)
     if node.right:
       stack.append(node.right)
     res.append(node.val)
   return res[:: - 1 ]

二叉树的层次遍历 。

迭代 。

?
1
2
3
4
5
6
7
8
9
10
11
def levelorder(root):
   queue = [root]
   res = []
   while queue:
     node = queue.pop( 0 )
     if node.left:
       queue.append(node.left)
     if node.right:
       queue.append(node.right)
     res.append(node.val)
   return res

希望本文所述对大家Python程序设计有所帮助.

原文链接:https://blog.csdn.net/wenkenza5368/article/details/79573333 。

最后此篇关于Python实现二叉树的常见遍历操作总结【7种方法】的文章就讲到这里了,如果你想了解更多关于Python实现二叉树的常见遍历操作总结【7种方法】的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com