# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
The test system has defined the nodes , Node value is int type , without L/R, Its value is None Not the example null
My general idea flow is :
stack = []
result = []
visit = root
while visit:
while visit.left:
# When there is a left child
if isinstance(visit.left, int):
# Left the child -> leaf
result.append(visit.left)
# Access the left node
else:
# Left the child -> subtree
stack.append(visit)
visit = visit.left
# Stack current node , Visit left child
result.append(visit.val)
# Access root
while stack and not visit.right:
# Stack is not empty. 、 The visited node has no right child
visit = stack.pop()
result.append(visit.val)
if isinstance(visit.right, int):
# The right child -> leaf
result.append(visit.right)
else:
# The right child -> subtree
visit = visit.right
return result
The test of the buckle is not accurate , Many tests fluctuate a little
With the development of societ
Jane Medium : This paper gives