LeetCode 366 | Find Leaves of Binary Tree | Solution Explained (Java + Whiteboard)
Вставка
- Опубліковано 11 жов 2024
- Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
Running Time: O(N)
Space Complexity: O(N)
Always be pluggin:
Slack Channel: join.slack.com...
Github: github.com/xav...
Facebook: / xavier.hollingsworth.3
Instagram: / xavierelon
LinkedIn: / xavier-hollingsworth-5...
Twitter: / elon_xavier
Need more white board walk through along with code.
Indeed, may be a hard concept to understand, but an easy problem if you are experienced with recursion problems. I think your solution explains itself along with the whiteboard example. Thanks for sharing.
I had this problem interviewed at Google back in 2021, but not binary tree, it was N-ary Tree. I was using topological sorting to resolve it.(make every node pointing to its parent node) Not at good as yours though.
Great Job!! Very concise explanation....thank you.
Hi Xavier, thank you for your work - keep on going! I do think though that it was worth mentioning how and way the individual levels got created in the final answer.
Yes I try to address this but it is hard with recursion. I am still working on it
The way I look at it is that the Tree levels are indices in the resulting list (Zero-based). The recursion execution ensures that a new index (new ArrayList) is added only the first time when a new level is discovered.
Yes I can visualize it in my head but have trouble figuring out how to draw it out on the white board for you guys
thank you !!
holy shit I think I finally understand recursion
Haha glad you figured it out. It’s a tricky topic
Smart to think of it as layers and to set the not root to -1 to make the math easier to add the root values.
thanks, but we don't remove the leaves actually, right?
You can if you want but it is not required. I wrote a line in a different submission that erases the leaves and it still passes all the test cases
It helped, thanks!
You’re welcome
Standard optimal solution, very poor explanation...