0 topic description
Link to the original title of Leetcode: Preorder traversal of binary tree
# 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
1 Recursive solution
Depth First Search (DFS)
In this strategy, we use depth as a priority to start from the root and reach a certain leaf, and then return to the root to reach another branch.
The depth-first search strategy can be subdivided into pre-order traversal, middle-order traversal and post-order traversal according to the relative order of the root node, left child, and right child.
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
Algorithm complexity
Time complexity: O (n) O(n)O ( n ) , wherennn is the number of binary tree nodes. In the traversal of the binary tree, each node will be visited once and only once.
Space complexity:O (n) O(n)O ( n ) . The space complexity depends on the recursive stack depth, and the stack depth can reachO (n) O(n)when the binary tree is a chainO ( n ) level.
2 Iterative solution (stack)
Breadth First Search (BFS)
We visit the entire tree layer by layer in order of height, and higher-level nodes will be visited before lower-level nodes.
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
White, Gray = 0, 1
res = []
stack = [(White,root)]
while stack:
color, node = stack.pop()
if not node: continue
if color == White:
stack.append((White,node.right))
stack.append((White,node.left))
stack.append((Gray,node))
else:
res.append(node.val)
return res
Algorithm complexity
Time complexity: visit each node exactly once, time complexity is O (N) O (N)O ( N ) , whereNNN is the number of nodes, which is the size of the tree.
Space complexity: depends on the structure of the tree, the worst case is to store the entire tree, so the space complexity isO (N) O(N)O ( N )。
3 Morris preorder traversal
The method is based on Morris' article and can optimize the space complexity. The algorithm does not use extra space, only the final output result needs to be saved. If the result is output in real time, the space complexity is O (1) O(1)O ( 1 )。
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
node, res = root, []
while node:
if not node.left:
res.append(node.val)
node = node.right
else:
pre = node.left
while pre.right and pre.right is not node:
pre = pre.right
if not pre.right:
res.append(node.val)
pre.right = node
node = node.left
else:
pre.right = None
node = node.right
return res
Algorithm complexity
Time complexity: O (n) O(n)O ( n ) , wherennn is the number of nodes in the binary search tree. In Morris traversal, each node will be visited twice, so the total time complexity isO (2 n) O(2n)O ( 2 n ) =O (n) O (n)O ( n ) .
Space complexity:O (1) O(1)O ( 1 )。
Reference
In-order traversal of binary tree-Python implements three solutions
Leetcode