LeetCode 107. Binary Tree Level Order Traversal II 二叉树的层次遍历 II

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

解法一:迭代
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> result;
        if(root==nullptr)
            return result;
        
        queue<TreeNode*> current,next;
        vector<int> level;
        current.push(root);
        
        while(!current.empty())
        {
            while(!current.empty())
            {
                TreeNode* node=current.front();
                current.pop();
                level.push_back(node->val);
                if(node->left!=nullptr)
                    next.push(node->left);
                if(node->right!=nullptr)
                    next.push(node->right);
            }
            result.push_back(level);
            level.clear();
            swap(next,current);
        }
        reverse(result.begin(),result.end());
        return result;
        
    }
    
};

解法二:递归

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> result;
        traverse(root,1,result);
        reverse(result.begin(),result.end());
        return result;
        
    }
    
    void traverse(TreeNode* root,size_t level,vector<vector<int>> &result)
    {
        if(!root)
            return;
        if(level>result.size())
            result.push_back(vector<int>());
        result[level-1].push_back(root->val);
        traverse(root->left,level+1,result);
        traverse(root->right,level+1,result);
    }
};

猜你喜欢

转载自blog.csdn.net/qq_34501451/article/details/83035797