``````class Stack(object):

def __init__(self, size_limit=None):
self._size_limit = size_limit
self.elements = []
self._size = 0

# 进栈，判断是否越界
def push(self, value):
if self._size_limit is not None and len(self.elements) > self._size_limit:
raise IndexError("Stack is full")
else:
self.elements.append(value)
self._size += 1

# 判断栈是否为空
def is_empty(self):
return self._size == 0

# 栈清空
def clear(self):
self.elements = []
self._size = 0

# 访问元素数量
def size(self):
return self._size

# 查询栈顶元素
def top(self):
return self.elements[-1]

# 弹出栈顶元素
def pop(self):
val = self.elements.pop()
self._size -= 1
return val``````

``````class Node:
def __init__(self, val):
self.val = val
# 左孩子
self.lchild = None
# 右孩子
self.rchild = None

if __name__ == "__main__":
# 建树
root = Node(0)
node1 = Node(1)
root.lchild = node1
node2 = Node(2)
root.rchild = node2
node3 = Node(3)
node1.lchild = node3
node4 = Node(4)
node1.rchild = node4
node5 = Node(5)
node2.rchild = node5``````

``````          0
/ \
1   2
/ \    \
3   4    5``````

``````
def dfs(node):
if node is None:
return
dfs(node.lchild)
print(node.val)
dfs(node.rchild)``````

``````class Node:
def __init__(self, val):
self.val = val
self.lchild = None
self.rchild = None
self.flag = True``````

``````# 使用我们自己刚刚创建的数据结构
stack = Stack()
# 插入根节点
stack.push(root)

while not stack.is_empty():
# 获取栈顶元素，也就是当前遍历的节点
tmp = stack.top()
# 如果不曾回溯过，并且左子树存在
while tmp.flag and tmp.lchild is not None:
# 回溯标记置为False
tmp.flag = False
# 栈顶push左孩子
stack.push(tmp.lchild)
# 往左遍历
tmp = tmp.lchild
# 弹出栈顶
tmp = stack.pop()
# 此时说明左节点已经遍历完了，输出
print(tmp.val)
# 往右遍历
if tmp.rchild is not None:
stack.push(tmp.rchild)``````