Source: https://leetcode.com/problems/find-leaves-of-binary-tree/
Given the root of a binary tree, collect the tree nodes as if you were doing this: Collect all the leaf nodes. Remove all the leaf nodes. Repeat until the tree is empty.
/*** Definition for a binary tree node.* function TreeNode(val, left, right) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }*//*** @param {TreeNode} root* @return {number[][]}*/// O(NlogN) time for sorting, O(N) space for node heightsvar findLeaves = function(root) {const nodeHeights = [];// Recursive function to get all the heights of each nodeconst getHeight = (currentRoot) => {if (currentRoot === null) {return -1;}const leftHeight = getHeight(currentRoot.left);const rightHeight = getHeight(currentRoot.right);const currentHeight = Math.max(leftHeight, rightHeight) + 1;nodeHeights.push([currentHeight, currentRoot.val]);return currentHeight;};// Get the heights of all the nodes in the treegetHeight(root);// Sort the nodes by height in ascending ordernodeHeights.sort((a, b) => a[0] - b[0]);// Build the leaves solution based on the sorted node heightsconst leavesHeights = [];let height = 0;let i = 0;while (i < nodeHeights.length) {const currentLeaves = [];// While we're on the same height, we keep adding to the current leaves arraywhile (i < nodeHeights.length && nodeHeights[i][0] === height) {currentLeaves.push(nodeHeights[i][1]);i++;}leavesHeights.push(currentLeaves);height++;}return leavesHeights;};