树深度优先遍历分为三种:前序、中序以及后序。
1.前序优先遍历:
class TreeNode():
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def preorder(self, root):
if root is None:
return ''
print(root.val)
if root.left:
self.preorder(root.left)
if root.right:
self.preorder(root.right)
2.中序遍历:
def midorder(self,root):
if not root:
return ''
if root.left:
self.midorder(root.left)
print(root.val)
if root.right:
self.midorder(root.right)
3.后序遍历:
def midorder(self,root):
if not root:
return ''
if root.left:
self.midorder(root.left)
if root.right:
self.midorder(root.right)
print(root.val)