递归太简单了不写了
后序遍历
#后序遍历
# 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 postorderTraversal(self, root: TreeNode) -> List[int]:
res=[]
p=[]
pre=None
r=root
while p or r:
while r:#找最左子节点并维护栈
p.append(r)
r=r.left
r=p.pop()
if not r.right or r.right==pre:
res.append(r.val)
pre=r
r=None
else:
p.append(r)#当前节点有右节点返回栈
r=r.right
return res
中序遍历
# 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 inorderTraversal(self, root: TreeNode) -> List[int]:
stack=[]
res=[]
while stack or root:
if root:
stack.append(root)
root=root.left
else:
root=stack.pop()
res.append(root.val)
root=root.right
return res
前序遍历
用栈
# 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]:
p=[root]
res=[]
while p:
r=p.pop()
if r:
res.append(r.val)
p.append(r.right)
p.append(r.left)
return res