leetcode+ 二叉树BFS,用栈存储每一层,最后就能输出从底层到顶层每一层

点击打开链接
class Solution {
public:
    vector> levelOrderBottom(TreeNode* root) {
        vector> res;
        queue Q;
        if(root) Q.push(root);
        stack> st;
        while (!Q.empty()) {
            int count = 0;
            int levCount = Q.size();
            vector levNode;
            while (count < levCount) {
                TreeNode* curNode = Q.front();
                Q.pop();
                levNode.push_back(curNode->val);
                if(curNode->left) Q.push(curNode->left);
                if(curNode->right) Q.push(curNode->right);
                count+=1;
            }
            st.push(levNode);
        }
        while (!st.empty()) {
            res.push_back(st.top());
            st.pop();
        }
        return res;
    }
};

你可能感兴趣的:(Leetcode)