二叉树的遍历(python)
2022/1/10 9:03:47
本文主要是介绍二叉树的遍历(python),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一、中序
1. 递归
class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] res = [] res.extend(self.inorderTraversal(root.left)) res.append(root.val) res.extend(self.inorderTraversal(root.right)) return res
2. 迭代
class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: p = root stack = [] res = [] while p or stack: while p: stack.append(p) p = p.left p = stack.pop() res.append(p.val) p = p.right return res
3. Morris
class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: res = [] p = root while p: if p.left: predecessor = p.left while predecessor.right: predecessor = predecessor.right predecessor.right = p temp = p p = p.left temp.left = None else: res.append(p.val) p= p.right return res
二、前序
1. 递归
class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] res = [root.val] res.extend(self.inorderTraversal(root.left)) res.extend(self.inorderTraversal(root.right)) return res
2. 迭代
class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: res = [] stack = [] p = root while stack or p: while p: res.append(p.val) stack.append(p.right) p = p.left p = stack.pop() return res
3. Morris
class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: res = list() p1 = root while p1: p2 = p1.left if p2: while p2.right and p2.right != p1: p2 = p2.right if not p2.right: res.append(p1.val) p2.right = p1 p1 = p1.left continue else: p2.right = None else: res.append(p1.val) p1 = p1.right return res
三、后序
1. 递归
class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] res = [] res.extend(self.inorderTraversal(root.left)) res.extend(self.inorderTraversal(root.right)) res.append(root.val) return res
2. 迭代
class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: res = [] stack = [] p= root while stack or p: while p: res.append(p.val) stack.append(p.left) p= p.right p= stack.pop() res.reverse() return res
3. Morris
class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: def addPath(node: TreeNode): count = 0 while node: count += 1 res.append(node.val) node = node.right i, j = len(res) - count, len(res) - 1 while i < j: res[i], res[j] = res[j], res[i] i += 1 j -= 1 res = [] p1 = root while p1: p2 = p1.left if p2: while p2.right and p2.right != p1: p2 = p2.right if not p2.right: p2.right = p1 p1 = p1.left continue else: p2.right = None addPath(p1.left) p1 = p1.right addPath(root) return res
这篇关于二叉树的遍历(python)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-03用FastAPI掌握Python异步IO:轻松实现高并发网络请求处理
- 2025-01-02封装学习:Python面向对象编程基础教程
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型