23.01.09 Today’s Leetcode
Binary Tree Preorder (easy)
# with DFS
class Solution:
res = []
def dfs(self, root):
if root == None:
return
self.res.append(root.val)
self.dfs(root.left)
self.dfs(root.right)
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
self.res = []
self.dfs(root)
return self.res
# with queue
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans, stack = [] , []
stack.append(root)
while stack:
curNode = stack.pop()
if curNode:
ans.append(curNode.val)
stack.append(curNode.right)
stack.append(curNode.left)
return ans