describe

Given the root of a binary tree, return the preorder traversal of its nodes’ values.

Example 1:

Input: root = [1,null,2,3]
Output: [1,2,3]
Copy the code

Example 2:

Input: root = []
Output: []
Copy the code

Example 3:

Input: root = [1]
Output: [1]
Copy the code

Example 4:

Input: root = [1,2]
Output: [1,2]
Copy the code

Example 5:

Input: root = [1, NULL,2] Output: [1,2]Copy the code

Note:

The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
Copy the code

parsing

It’s a sequential traversal of a binary tree. The values of the nodes are placed directly into the result list in a recursive order, root first, left then right.

answer

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        r = []
        def pre(root):
            if not root:
                return 
            r.append(root.val)
            pre(root.left)
            pre(root.right)
        pre(root)
        return r
        	      
		
Copy the code

The results

Given in the Python online submission for Binary Tree Traversal. Memory Usage: 10000 ms Given in Python online submissions for Binary Tree Preorder Traversal.Copy the code

Original link: leetcode.com/problems/bi…

Your support is my biggest motivation