Binary Tree Preorder Traversal LeetCode Solution | Easy Approach

Minimum Cost to Merge Stones
Share:

Binary Tree Preorder Traversal 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]

Constraints:

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

Binary Tree Preorder Traversal Solutions

Time: O(n)
Space: O(h)

C++

class Solution {
 public:
  vector<int> preorderTraversal(TreeNode* root) {
    vector<int> ans;
    preorder(root, ans);
    return ans;
  }

 private:
  void preorder(TreeNode* root, vector<int>& ans) {
    if (!root)
      return;

    ans.push_back(root->val);
    preorder(root->left, ans);
    preorder(root->right, ans);
  }
};

Java

 class Solution {
  public List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> ans = new ArrayList<>();
    preorder(root, ans);
    return ans;
  }

  private void preorder(TreeNode root, List<Integer> ans) {
    if (root == null)
      return;

    ans.add(root.val);
    preorder(root.left, ans);
    preorder(root.right, ans);
  }
}

Python


class Solution:
  def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
    ans = []

    def preorder(root: Optional[TreeNode]) -> None:
      if not root:
        return

      ans.append(root.val)
      preorder(root.left)
      preorder(root.right)

    preorder(root)
    return ans

Watch Tutorial

Checkout more Solutions here

Leave a Comment

Your email address will not be published. Required fields are marked *

x