python树栈
时间: 2023-06-21 22:20:27 浏览: 84
python tree
树和栈都是非常常见的数据结构,Python也提供了相应的实现方法。下面是一些Python树和栈的示例代码:
1. 树的实现示例代码:
```
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
```
2. 栈的实现示例代码:
```
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
if not self.is_empty():
return self.stack.pop()
def is_empty(self):
return len(self.stack) == 0
def peek(self):
if not self.is_empty():
return self.stack[-1]
def size(self):
return len(self.stack)
```
希望这些示例代码能够对你有所帮助!
阅读全文