难度
中
题目
请用熟悉的编程语言实现树的先序遍历
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorderTraversal(root):
result = []
if root is None:
return result
result.append(root.val)
result += TreeNode.preorderTraversal(root.left)
result += TreeNode.preorderTraversal(root.right)
return result
if __name__ == '__main__':
root = TreeNode(1)
root.left = TreeNode(2, TreeNode(4), TreeNode(5))
root.right = TreeNode(3)
print(TreeNode.preorderTraversal(root))