当前位置:网站首页>小黑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 中序遍历 未来实现
边栏推荐
- [QNX Hypervisor 2.2用户手册]10.4 vdev hpet
- [Paper Notes KDD2021] MixGCF: An Improved Training Method for Graph Neural Network-based Recommender Systems
- 使用OpenCV实现一个文档自动扫描仪
- Service Mesh落地路径
- 3D建模师为了让甲方爸爸过稿,还可以这么做,就是在赚血汗钱啊
- 【内存操作函数内功修炼】memcpy + memmove + memcmp + memset(四)
- d枚举生成位
- web3.js
- kernel问题定位手段总结
- 年薪50W+的测试工程师都在用这个:Jmeter 脚本开发之——扩展函数
猜你喜欢
good luck
Pytest learning - fixtures
App测试和Web测试的区别
【3D建模制作技巧分享】ZBrush如何使用Z球
407. 接雨水 II
【内存操作函数内功修炼】memcpy + memmove + memcmp + memset(四)
使用OpenCV实现一个文档自动扫描仪
从“草原牛”到“数字牛”:蒙牛的数字化转型之道
【SSR服务端渲染+CSR客户端渲染+post请求+get请求+总结】
PID Controller Improvement Notes No. 7: Improve the anti-overshoot setting of the PID controller
随机推荐
Shell expect real cases
Jbpm3.2 开发HelloWorld (简单请假流程)客户端
Community Sharing|Tencent Overseas Games builds game security operation capabilities based on JumpServer
【3D建模制作技巧分享】如何使用ZBrush导出效果图
Implementing class target method exception using proxy object execution
I was rejected by the leader for a salary increase, and my anger rose by 9.5K after switching jobs. This is my mental journey
基于深度学习的路面坑洞检测(详细教程)
Web安全开发 | 青训营笔记
软件测试技术之如何编写测试用例(4)
C语言实现扫雷 附带源代码
956. 最高的广告牌
【3D建模制作技巧分享】Maya模型如何导入zbrush
360市值四年蒸发3900亿,政企安全能救命吗?
使用OpenCV实现一个文档自动扫描仪
One trick to cure pycharm DEBUG error UnicodeDecodeError: 'utf-8' codec can't decode
Kernel函数解析之kernel_restart
App测试和Web测试的区别
【字符串函数内功修炼】strlen + strstr + strtok + strerror(三)
[QNX Hypervisor 2.2用户手册]10.6 vdev mc146818
七牛云图片上传