Skip to content

Latest commit

 

History

History
42 lines (32 loc) · 981 Bytes

Binary Tree Preorder Traversal.md

File metadata and controls

42 lines (32 loc) · 981 Bytes

Provided Code

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
}

Solution

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

    private void preorderTraversal(TreeNode node, List<Integer> list) {
        if (node != null) {
            list.add(node.val);
            preorderTraversal(node.left, list);
            preorderTraversal(node.right, list);
        }
    }
}

Time/Space Complexity

  • Time Complexity: O(n) since we must visit all nodes.
  • Space Complexity: O(log n) on balanced tree. O(n) otherwise.

Notes

The follow-up question asks us for an iterative solution, but there is no benefit to that solution as neither the time or space complexity is improved by solving the problem iteratively.

Links