0

I started working on some code to invert a binary tree and I got the below. It's pretty straightforward, but I didn't understand what is the "TreeNode() {}" iin the commented section accomplishing? Thank you!

/**
 * 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 TreeNode invertTree(TreeNode root) {
        
    }
}
sgx
  • 1,265
  • 3
  • 19
  • 36

1 Answers1

1

TreeNode() {} is a no-argument constructor (which, in Java, is different from a default constructor). It has no body, and therefore accomplishes nothing. Since Java initializes all member variables to their default values upon creation, before the constructor is even invoked, the blank constructor body will leave these values in their default state.

Note that since Objects are initialized to null, attempting to access left or right before assigning them will result in an error.

Nick Reed
  • 4,989
  • 4
  • 17
  • 37
  • Thanks - this is great! I guess I'm still a little confused as to what is the need to include that, i.e. why include code that doesn't accomplish anything? – sgx Feb 15 '21 at 01:37
  • 1
    Have a look at [this question](https://stackoverflow.com/q/48553000/7431860) and its answers for a bit more info on why one might include a no-arg constructor in their class. – Nick Reed Feb 15 '21 at 01:42