smit
smit

Reputation: 59

Error: object cannot be converted to TreeNode type (stack error while passing it in function) a question on trees on LeetCode

I'm working on the LeetCode problem https://leetcode.com/problems/binary-tree-preorder-traversal.

When I create the stack in the solution method and pass it to the traverse method, the compiler gives error: object cannot be converted to TreeNode (type).

However, when I put that line inside the traverse method along with the push(root) line, then the error is gone.

I don't understand why this difference occurs.

The error occurs on line TreeNode temp=s.peek();

My code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> a=new ArrayList<>();
        Stack<TreeNode> s=new Stack<TreeNode>();
        s.push(root);
        traverse(root,s,a);
        return a;
    }

    void traverse(TreeNode root,Stack s,List<Integer> a) {
        if(root==null) return;
         
        TreeNode temp=s.peek();
        
        while(!s.isEmpty())
        {   
            TreeNode temp=s.peek();
            a.add((temp.val));
            s.pop();
            if(temp.right!=null)
                s.push((temp.right));
            if(temp.left!=null)
                s.push((temp.left));
        }
    }
}

Upvotes: 1

Views: 880

Answers (1)

ggorlen
ggorlen

Reputation: 57115

You forgot to add generics to your Stack parameter. The signature should be

void traverse(TreeNode root, Stack<TreeNode> s, List<Integer> a);
//                                ^^^^^^^^^^

Otherwise, TreeNode temp = s.peek(); doesn't make sense on a structure implicitly typed Stack<Object>. You'd need to cast the Object to a TreeNode in order to pass compilation, which is unsafe and unnecessary.

Conversely, in case it's not obvious, when you move the declaration and initialization into the method and remove the parameter, Stack<TreeNode> s = new Stack<TreeNode>(); correctly specifies the generic type so the peek assignment to TreeNode types will compile.

Upvotes: 1

Related Questions