python实现二叉树题的相关代码-左程云视频笔记-更新中
2023-09-27 14:29:29 时间
python实现二叉树题和代码
左程云视频笔记和python实现
b站视频链接
二叉树
遍历
- 二叉树三种遍历方式
"先序遍历,先输出根,再遍历左,遍历右"
def preOrder(node):
if node == None:
return
print(node.val)
preOrder(node.left)
preOrder(node.right)
"中序遍历,先遍历左,再输出,再遍历右"
def midOrder(node):
if node == None:
return
preOrder(node.left)
print(node.val)
preOrder(node.right)
"后序遍历,先遍历左,遍历右,再输出"
def backOrder(node):
if node == None:
return
preOrder(node.left)
preOrder(node.right)
print(node.val)
- 非递归实现
"非递归实现先序遍历,中序和后序也是类似"
def preOrderUnrecur(node):
print("pre-order:")
if node:
stack = [node] # python的列表可以当作栈
while len(stack): # 栈不空
head = stack.pop() # 弹出最后一个元素
print(head.val,' ',end='')
if head.right:
stack.append(head.right)
if head.left:
stack.append(head.left)
寻找最近公共祖先
- 思路
- 代码
# o1,o2就是两个待寻找祖先的结点
def LowestAncestor(head,o1,o2):
if head == None or head == o1 or head == o2:
return head
left = LowestAncestor(head.left,o1,o2)
right = LowestAncestor(head.righr,o1,o2)
# 如果左右子树都不为空,就返回自己
if left and right:
return head
# 返回为空的另一个结点
return left if left else right
给定结点,找后继结点
- 后继结点:中序遍历中,当前结点的下一个结点就称后继结点
- 结点结构体包括左孩子,右孩子,父亲,三个指针
- 代码
def getLeftMost(node):
if node == None:
return node
while node.left != None:
node = node.left
return node
def getSuccessorNode(node):
if node == None:
return node
if node.right != None:
return getLeftMost(node.right)
else: # 无右子树
parent = node.parent
while parent != None and parent.left != node:
node = parent
parent = node.parent
return parent
相关文章
- 【华为OD机试真题 python】 二叉树层序遍历【2022 Q4 | 200分】
- 零基础如何开始学习 Python?看完这篇从小白变大牛!
- 我想要月入过万在尝试一下Python这个职业后发现这也太简单了
- python在es中scroll用法详解
- 14 python - break和continue
- 【python】剑指 Offer 55 - I. 二叉树的深度
- Python框架级编程的能力要求
- 《树莓派Python编程入门与实战(第2版)》——导读
- Python 网络编程之过多线程在两个单独的 GUI 之间进行通信(教程含完整源码)
- 【华为OD机试真题 java、python、c++】微服务的集成测试【2022 Q4 100分】
- Python写MySQL数据库乱码
- 【Leetcode】101:对称二叉树(Python)
- Python自动化交易学习笔记(十一)——引入了移动平均值这一技术指标,股票比亚迪002594
- python @classmethod 类方法与 @staticmethod 静态方法 标准模块 abc 提供的 @abstractmethod 抽象方法
- 二叉树的后序遍历(Python+C两种都有)
- Python入门学习笔记第十章——文件和异常~~~