Created
July 6, 2025 07:04
-
-
Save gbajaj/1211f5b7222fbdc05d6925b5fd247e05 to your computer and use it in GitHub Desktop.
Traverses and collects node values in a BFS Tree Traversal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| fun levelOrder(root: TreeNode?): List<List<Int>> { | |
| val twoDList = mutableListOf<MutableList<Int>>() | |
| levelOrderRecursive(root, twoDList, 0) | |
| return twoDList | |
| } | |
| fun levelOrderRecursive(root: TreeNode?, list: MutableList<MutableList<Int>>, level: Int) { | |
| if (root == null) return | |
| // Since we might not have a list existing at that level, lets add if needed | |
| if (list.size == level) list.add(mutableListOf<Int>()) | |
| list[level].add(root.`val`) | |
| levelOrderRecursive(root.left, list, level + 1) | |
| levelOrderRecursive(root.right, list, level + 1) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment