2

While coding for a question about binary search tree on the Leetcode, I came with situation below:

public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { public List<Integer> inorderTraversal (TreeNode root) { // the variables below are defined by myself. Stack <TreeNode> stack = new Stack<TreeNode>(); ArrayList<Integer> res = new ArrayList<Integer>(); TreeNode curr = root; ... } } 

In the last line, I define a TreeNode and make it equal to root. But if I wrote as

TreeNode curr = new TreeNode() 

The compiler raises an error. I don't know why I cannot define a TreeNode as a temp variable in this way.

0

3 Answers 3

4

Your TreeNode class does not have a no-argument constructor.

Since you have defined a constructor with int parameter the compiler will not create a default constructor for you.

Something like this (assuming it makes sense) will work:

TreeNode cust = new TreeNode(someIntValue); 
Sign up to request clarification or add additional context in comments.

1 Comment

Oh! Got it ! Thank you very much!
2

The TreeNode constructor has the parameter int x, so if you only write "TreeNode curr = new TreeNode ();", then there will be an error. All you need to do is add an int for the parameter.

Solution: "TreeNode curr = new TreeNode (4);"

Just add any int value.

Comments

2

Java lets you use the default constructor (a constructor with no args) only in case you didn't explicitly created your own constructor in the class. Once you create your own constructor, in your case TreeNode(int x) { val = x; } you can no longer use the default constructor for that class.

1 Comment

Yeah! Thank you so much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.