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.