二叉树的遍历(递归+迭代)
前序概念
前序遍历(又称先序遍历,即先序遍历根)
遍历顺序:根->左->右 2->1->3
遍历顺序: ABDEGJHCFIKL
二叉树前序遍历 递归
。
题目来源:leetcode
https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
# 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 preorderTraversal(self, root: TreeNode) -> List[int]:
return_list = []
# 前序遍历函数
def preorder(node):
# 递归的结束条件,节点为空
if node is None:
return
return_list.append(node.val)
preorder(node.left)
preorder(node.right)
# 递归实现中,后序遍历调整上面三个位置即可
preorder(root)
return return_list
二叉树前序遍历 迭代
。
# 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 preorderTraversal(self, root: TreeNode) -> List[int]:
simple_stack = []
if not root:
return simple_stack
# 用两个游标cursor1,2
cursor1 = root
while cursor1 is not None:
cursor2 = cursor1.left
if cursor2:
while cursor2.right is not None and cursor2.right != cursor1:
cursor2 = cursor2.right
if not cursor2.right:
simple_stack.append(cursor1.val)
cursor2.right = cursor1
cursor1 = cursor1.left
continue
else:
cursor2.right = None
else:
simple_stack.append(cursor1.val)
cursor1 = cursor1.right
return simple_stack
相当与 用while语句控制一个一个遍历 根->左->右
一个游标用于保存根节点,另一个用于访问右子树,如此往复,完成遍历