Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * 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) {}
- * };
- */
- class Solution {
- private:
- vector<vector<int>> solution;
- public:
- int getHeight(TreeNode *root) {
- // return -1 for null nodes
- if (!root)
- return -1;
- // first calculate the height of the left and right children
- int leftHeight = getHeight(root->left);
- int rightHeight = getHeight(root->right);
- // based on the height of the left and right children, obtain the height of the current (parent) node
- int currHeight = max(leftHeight, rightHeight) + 1;
- // create space for node located at `currHeight` if not already exists
- if(solution.size() == currHeight)
- solution.push_back({});
- // insert the value at the correct position in the solution array
- solution[currHeight].push_back(root->val);
- // return the height of the current node
- return currHeight;
- }
- vector<vector<int>> findLeaves(TreeNode* root) {
- solution.clear();
- getHeight(root);
- return solution;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement