先序遍历
利用栈,在pop之后在push子树
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
res = []
stack = [root]
while stack:
current = stack.pop()
if current:
res.append(current.val)
stack.append(current.right)
stack.append(current.left)
return res
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
res = []
res.append(root.val)
res += self.preorderTraversal(root.left)
res += self.preorderTraversal(root.right)
return res
中序遍历
class Solution:
def inorderTraversal(self, root):
if root ==None:
return[]
res=[]
res+=self.inorderTraversal(root.left)
res.append(root.val)
res+=self.inorderTraversal(root.right)
return res
利用栈,根节点其实可以看做一个左子树,然后push右子树
class Solution:
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root==None:
return[]
stack=[]
res=[]
while True:
while root:
stack.append(root)
root=root.left
if not stack:
return res
current=stack.pop()
res.append(current.val)
root=current.right
return res
后序遍历
可以和先序遍历比较,先序遍历在子树push之前将根节点pop出,而后续没有,并且利用tag指示是否是在左右子树都pop之后才可以pop根节点
class Solution:
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
stack = [root]
res = []
while stack:
cur = stack[-1]
if not cur:
stack.pop()
continue
if not cur.left and not cur.right:
res.append(stack.pop().val)
continue
stack.append(cur.right)
stack.append(cur.left)
cur.left, cur.right = None, None
return res
class Solution:
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
res=[]
res+=self.postorderTraversal(root.left)
res+=self.postorderTraversal(root.right)
res.append(root.val)
return res