Binary Tree Preorder Traversal
144. Binary Tree Preorder Traversal
Difficulty: Easy
Related Topics: Stack, Tree, DFS, Binary Tree
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]
Example 2:
Input: root = [] Output: []
Example 3:
Input: root = [1] Output: [1]
Code:
# 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 preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
values = []
stack = [root]
while stack:
node = stack.pop()
if node:
values.append(node.val)
stack.append(node.right)
stack.append(node.left)
return values
Feedbacks:
I found the values of elements in binary tree by iteratively. Make a stack to store a root. As root exists, I pop it and store it to values list, and append node.right and node.left to stack, and re-do the same steps continuously untill I get to null values.