Binary Tree Level Order Traversal II - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Thursday, 20 August 2020

Binary Tree Level Order Traversal II

Binary Tree Level Order Traversal II

 Binary Tree Level Order Traversal II


Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]
/**
 * 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:
    void helper(TreeNode *r, vector<vector<int>> &res, int i){
        if(!r) return;
        if(i==res.size())
            res.push_back(vector<int>());
        res[i].push_back(r->val);
        helper(r->left, res, i+1);
        helper(r->right, res, i+1);
    }
    
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> res;
        helper(root, res, 0);
        reverse(res.begin(), res.end());
        return res;
         
};
-----------------------------------------------------------------------------------                       
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        if(root==NULL)return {};
        queue<TreeNode*> q;                  
        q.push(root);
        vector<vector<int>> ans;
        while(!q.empty())
        {
            int s=q.size();
            vector<int> v;
            while(s--)
            {
                
                auto p=q.front();
                 q.pop();
                
                 v.push_back(p->val);
                if(p->left)
                    q.push(p->left);
                if(p->right)
                    q.push(p->right);
            }
            ans.insert(ans.begin(),v);
        }
        return ans;
    }
};