Search code examples
javalinked-listtreestackdeque

Define a Deque into LinkedList


I am reviewing a code pre-order binary tree using iterative method. Looks like they do:

Deque < TreeNode > stack = new LinkedList< TreeNode >();

Why not just do:

Deque < TreeNode > stack = new Deque < TreeNode >();

I dont see they use something particularly from LinkedList been used in the code.

public class PreOrder {  
  public static List<Integer> preorderTraversalIterative(TreeNode root) {
    List<Integer> preorder = new ArrayList<Integer>();
    if (root == null) {
      return preorder;
    }
    Deque<TreeNode> stack = new LinkedList<TreeNode>(); //Why?
    stack.offerFirst(root);
    while(!stack.isEmpty()) {
      TreeNode cur = stack.pollFirst();
      if (cur.right != null) {
        stack.offerFirst(cur.right);
      }
      if (cur.left != null) {
        stack.offerFirst(cur.left);
      }
      preorder.add(cur.key);
    }
    return preorder;
  }
} 

Solution

  • Deque is an interface; you cannot instantiate it without providing an implementation for all of its abstract methods, which is what LinkedList does already.