Try   HackMD

144.Binary Tree Preorder Traversal

tags: Easy,Tree,DFS,Stack,Binary Tree

144. Binary Tree Preorder Traversal

題目描述

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

範例

Example 1:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

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

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

Constraints:

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

Follow up: Recursive solution is trivial, could you do it iteratively?

解答

Javascript

recursive

function preorderTraversal(root) { const result = []; if (root === null) return result; result.push(root.val); result.push(...preorderTraversal(root.left)); result.push(...preorderTraversal(root.right)); return result; }

iterative

function preorderTraversal2(root) { const result = []; if (root === null) return result; const stack = [root]; while (stack.length > 0) { const node = stack.pop(); result.push(node.val); if (node.right !== null) stack.push(node.right); if (node.left !== null) stack.push(node.left); } return result; }

Marsgoat Jan 9, 2023

Python

class Solution: def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: if not root: return root traversal, stk = [], [root] while stk: node = stk.pop() traversal.append(node.val) if node.right: stk.append(node.right) if node.left: stk.append(node.left) return traversal

Ron Chen Jan 9, 2023

Reference

回到題目列表