当前位置:网站首页>小黑leetcode冲浪:94. 二叉树的中序遍历
小黑leetcode冲浪:94. 二叉树的中序遍历
2022-08-04 23:13:00 【小黑无敌】
小黑答案:递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
arr = []
if not root:
return arr
def mid_root(node):
if node:
mid_root(node.left)
arr.append(node.val)
mid_root(node.right)
mid_root(root)
return arr

小黑答案:非递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
arr = []
if not root:
return arr
q = []
node = root
# 将根结点所有做孩子入栈
while node:
q.append(node)
node = node.left
while q:
# 结点出栈
node = q.pop()
# 打印
arr.append(node.val)
# 开始便利右侧孩子
temp = node.right
while temp:
q.append(temp)
temp = temp.left
return arr

迭代法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
arr = []
if not root:
return arr
q = []
node = root
while node or q:
while node:
q.append(node)
node = node.left
node = q.pop()
arr.append(node.val)
# 拐向右面
node = node.right
return arr

方法三:Morris 中序遍历 未来实现
边栏推荐
猜你喜欢

一点点读懂cpufreq(一)

PID控制器改进笔记之七:改进PID控制器之防超调设定
![[Cultivation of internal skills of string functions] strncpy + strncat + strncmp (2)](/img/9f/9221c081cfa86caccbbd02916a6208.png)
[Cultivation of internal skills of string functions] strncpy + strncat + strncmp (2)

【游戏建模模型制作全流程】在ZBrush中雕刻恶魔城男性角色模型

逆序对的数量

轮播图动态渲染

ffplay视频播放原理分析

Community Sharing|Tencent Overseas Games builds game security operation capabilities based on JumpServer

仪表板展示 | DataEase看中国:数据呈现中国资本市场

【内存操作函数内功修炼】memcpy + memmove + memcmp + memset(四)
随机推荐
956. 最高的广告牌
【3D建模制作技巧分享】ZBrush模型制作流程:地精
生产者消费者问题
SSM整合完整流程讲解
MYS-6ULX-IOT 开发板测评——使用 Yocto 添加软件包
【字符串函数内功修炼】strcpy + strcat + strcmp(一)
社区分享|腾讯海外游戏基于JumpServer构建游戏安全运营能力
Literature reading ten - Detect Rumors on Twitter by Promoting Information Campaigns with Generative Adversarial Learn
[Cultivation of internal skills of string functions] strcpy + strcat + strcmp (1)
Pytest learning - fixtures
Go 编程语言(简介)
容联云发送短信验证码
Linux系统重启和停止Mysql服务教程
Both synchronized and ReentrantLock are smooth, because they are reentrant locks, and a thread will not deadlock if it takes the lock multiple times. We need reentrant locks
typeScript-promise
逆序对的数量
golang打开文件和读写文件
2022/8/3
Shell expect 实战案例
堪称奔驰“理财产品”,空间媲美宝马X5,采用了非常运动的外观