Skip to content

feat(cpp): add the default TreeNode constructor - #419

Merged
j178 merged 1 commit into
j178:masterfrom
j-sperling:add-treenode-default-ctor
Aug 18, 2026
Merged

feat(cpp): add the default TreeNode constructor#419
j178 merged 1 commit into
j178:masterfrom
j-sperling:add-treenode-default-ctor

Conversation

@j-sperling

Copy link
Copy Markdown
Contributor

Problem

LeetCode's own C++ boilerplate for tree problems declares the no-argument constructor:

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

testutils/cpp/LC_IO.h declares only the latter two. So a solution that calls new TreeNode() — common in tree-building and serialize/deserialize problems — compiles on the judge and fails to compile locally:

error: no matching function for call to 'TreeNode::TreeNode()'

That is the exact case local testing exists to catch, and here it produces a false negative against code the judge accepts.

ListNode in this same header already carries the matching set of three, which makes the asymmetry easy to miss until a tree problem runs into it.

Change

One line, restoring parity with both LeetCode's boilerplate and ListNode.

Verified with the CI command (g++ -std=c++17 -O2 -o tests tests.cpp && ./tests): all 15 existing tests pass.

Filed separately from #418 so the two can be judged on their own merits — that one is a bug fix, this one touches a public struct's API.

LeetCode's own C++ boilerplate declares four TreeNode constructors, including
the no-argument one. This header declares only two, so a solution that calls
new TreeNode() compiles on the judge and fails to compile locally - the case
local testing exists to catch.

ListNode already carries the matching set, so the asymmetry is easy to miss
until a tree problem hits it.
@j178 j178 added the bug Something isn't working label Aug 18, 2026
@j178
j178 merged commit a80639d into j178:master Aug 18, 2026
2 checks passed
@j178

j178 commented Aug 18, 2026

Copy link
Copy Markdown
Owner

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants