python二叉树中序遍历迭代法
2021/11/5 12:09:36
本文主要是介绍python二叉树中序遍历迭代法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
迭代法遍历二叉树:左根右
# 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: TreeNode) -> List[int]: if not root: return [] stack = [root] #存放具有左子树的根节点 numArrray = [] while( stack != [] ): root = stack.pop() while(root.left or root.right): #当前结点有子节点 while(root.left) : #存在左节点则一直往左遍历并保存 p = root.left root.left = None #遍历过的根节点左节点置零 stack.append(root)#避免重复遍历 root = p if root.right: #当前节点不存在左节点但存在右节点 numArrray.append(root.val)#输出当前节点 root = root.right #往右走一步 numArrray.append(root.val)#当前节点是子节点,直接输出 return numArrray
这篇关于python二叉树中序遍历迭代法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python