二叉树三种遍历方式的递归和非递归写法(python 实现)
2019-08-01 20:24
232 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_45024901/article/details/97969068
二叉树的遍历方式
二叉树的遍历有前序,中序和后序三种遍历方式。
前序遍历
前序遍历是指,对于树中的任意节点来说,先打印这个节点,然后再打印它的左子树,最后打印它的右子树。
递归写法
def preorder(root): if not root: return else: #todo preorder(root.left) preorder(root.right)
非递归写法
def preorder(root): node, stack = root,[] while node or stack: while node: stack.append(node) #这是第一次遇见它,所以直接进行操作 #todo node = node.left node = stack.pop() node = node.right
中序遍历
中序遍历是指,对于树中的任意节点来说,先打印它的左子树,然后再打印它本身,最后打印它的右子树。
递归写法
def inorder(root): if not root: return else: inorder(root.left) #todo inorder(root.right)
非递归写法
def inorder(root): node,stack = root,[] while node or stack: while node: stack.append(node) node = node.left node = stack.pop() #这是第二次遇见这个节点 #todo node = node.right
后序遍历
后序遍历是指,对于树中的任意节点来说,先打印它的左子树,然后再打印它的右子树,最后打印这个节点本身。
递归写法
def postorder(root): if not root: return else: postorder(root.left) postorder(root.right) #todo
非递归写法
def postorder(root): node, stack = root,[] while node or stack: while node: #todo 这里要和前序遍历是反向操作 #!!!!!!!!!!!! stack.append(node) node = node.right node = stack.pop() node = node.left
相关解释
二叉树三种遍历顺序的遍历路径是一样的。
但是前序遍历在第一次遇到节点的时候就访问,中序遍历则是第二次访问到该节点的时候进行访问,后序遍历则是第三次访问到该节点才进行实际的访问。
所以 在我们的非递归代码中,先序遍历第一次遇到就马上操作,中序遍历则是在栈弹出之后进行操作,而
后序遍历,后序遍历和前序遍历是对称的。
为了方便理解,贴一下leetcode前序遍历和后序遍历的代码,分别对应leetcode 144题和145题。
前序遍历题解:
class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: node, stack, res = root, [],[] while node or stack: while node: res.append(node.val) stack.append(node) node = node.left node = stack.pop() node = node.right return res
后序遍历题解:
class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: node, stack, res = root, [],[] while node or stack: while node: stack.append(node) res.insert(0,node.val) node = node.right node = stack.pop() node = node.left return res
请大家通过代码体会前序遍历和后序遍历是对称的的意思。
相关文章推荐
- 【python中二叉树的实现】python中二叉树的创建、三种方式递归遍历和非递归遍历
- 二叉树三种遍历方式的递归和循环实现
- 二叉树的三种遍历方式的循环和递归的实现方式
- 使用 Python 实现文件递归遍历的三种方式
- 二叉树的三种遍历方式的循环和递归的实现方式
- 详细讲解二叉树三种遍历方式的递归与非递归实现
- 二叉树的三种遍历方式的递归与非递归实现
- 用非递归方式实现二叉树的前、中、后三种遍历方法
- java使用递归,非递归方式实现二叉树的三种常见遍历方式
- 从递归的异同分析二叉树先序、中序、后序遍历共同流程并实现非递归方式的三种遍历。
- 二叉树的建立以及三种遍历方式的递归、非递归的实现
- 详细讲解二叉树三种遍历方式的递归与非递归实现
- 二叉树三种遍历方式 递归与非递归实现
- 二叉树的三种遍历方式的递归实现和非递归实现
- 二叉树的前序、中序、后序三种遍历的六种实现方式(递归、非递归)(C++)
- java使用递归,非递归方式实现二叉树的三种常见遍历方式
- 二叉树的三种遍历方式(递归与非递归详细实现)
- 二叉树三种遍历方式非递归实现
- 详细讲解二叉树三种遍历方式的递归与非递归实现
- 二叉树三种遍历方式的递归与非递归实现