-
Notifications
You must be signed in to change notification settings - Fork 0
tree #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
tree #15
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| package Trees; | ||
|
|
||
| /** | ||
| * 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 { | ||
| List<List<Integer>> res = new ArrayList<>(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix reusability bug by making result a local variable. The instance variable Move class Solution {
- List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
+ List<List<Integer>> res = new ArrayList<>();
- traverse(root, 0);
+ traverse(root, 0, res);
return res;
}
- private void traverse(TreeNode node, int depth) {
+ private void traverse(TreeNode node, int depth, List<List<Integer>> res) {
if (node == null) {
return;
}
if (res.size() == depth) {
res.add(new ArrayList<>());
}
res.get(depth).add(node.val);
- traverse(node.left, depth + 1);
- traverse(node.right, depth + 1);
+ traverse(node.left, depth + 1, res);
+ traverse(node.right, depth + 1, res);
}
🤖 Prompt for AI Agents |
||
|
|
||
| public List<List<Integer>> levelOrder(TreeNode root) { | ||
| traverse(root, 0); | ||
| return res; | ||
| } | ||
|
|
||
| private void traverse(TreeNode node, int depth) { | ||
| if (node == null) { | ||
| return; | ||
| } | ||
|
|
||
| if (res.size() == depth) { | ||
| res.add(new ArrayList<>()); | ||
| } | ||
|
|
||
| res.get(depth).add(node.val); | ||
| traverse(node.left, depth + 1); | ||
| traverse(node.right, depth + 1); | ||
| } | ||
|
|
||
|
|
||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add missing import statements.
The code uses
ListandArrayListbut the necessary import statements are missing, causing compilation failure.Add these imports after the package declaration:
📝 Committable suggestion
🤖 Prompt for AI Agents