Binary Tree Pre-order traversal

Problem link: https://leetcode.com/problems/binary-tree-preorder-traversal/

Ideas

We could do it in either iterative or recursive way.

Code

  1. Recursive solution:
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> results = new ArrayList<>();
        traverse(root, results);
        return results;
    }
    
    private void traverse(TreeNode root, List<Integer> results) {
        if (root == null)
        {
            return;
        }
        
        results.add(root.val);
        traverse(root.left, results);
        traverse(root.right, results);
    }
}
  • Time complexity: O(n) since we need to visit each node once.
  • Space complexity: O(n). For skew tree, the hight could be equal to the number of nodes.
  1. Iterative solution:
    If current node is not null, print its value and push it onto stack for late use when we need to visit its right child. Then set current node to its left child.
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> results = new ArrayList<>();
        Deque<TreeNode> st = new LinkedList<>();
        TreeNode current = root;
        
        while (current != null || !st.isEmpty())
        {
            if (current != null) {
                results.add(current.val);
                st.addFirst(current);
                current = current.left;
            } else {
                current = st.removeFirst();
                current = current.right;
            }
        }
        
        return results;
    }
}
  • Time: O(n).
  • Space: O(n). In the worst case, the stack will have to store all the elements for a tree.
posted on 2021-07-27 22:38  blackraven25  阅读(35)  评论(0)    收藏  举报