众所周知,二叉树存在三种常见遍历方式,分别为前序、中序和后序,节点读取顺序分别为中左右、左中右和左右中。这里提供一种通用的极简解法,三种遍历方法的代码如下。
前序遍历# 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: Optional[TreeNode]) -> List[int]:
ans = []
def dfs(node):
if not node:
return
ans.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
return ans
中序遍历
# 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: Optional[TreeNode]) -> List[int]:
ans = []
def dfs(node):
if not node:
return
dfs(node.left)
ans.append(node.val)
dfs(node.right)
dfs(root)
return ans
后序遍历
# 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: Optional[TreeNode]) -> List[int]:
ans = []
def dfs(node):
if not node:
return
dfs(node.left)
dfs(node.right)
ans.append(node.val)
dfs(root)
return ans
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)