力扣 面试题32 - III. 从上到下打印二叉树 III deque+bfs

https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/submissions/

力扣 面试题32 - III. 从上到下打印二叉树 III deque+bfs_第1张图片

思路: b f s bfs bfs时用双端队列就行了,每次处理一层。

/**
 * 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>> levelOrder(TreeNode* root) {
        deque<TreeNode*> d;
        d.push_front(root);
        int level=0,siz;
        TreeNode *fon;
        vector<vector<int>> ans;
        if(root==NULL)
            return ans;
        while(!d.empty())
        {
            siz=d.size();
            vector<int> tmp;
            if(++level&1)
            {
                while(siz--)
                {
                    fon=d.front();
                    d.pop_front();
                    tmp.push_back(fon->val);
                    if(fon->left!=NULL)
                        d.push_back(fon->left);
                    if(fon->right!=NULL)
                        d.push_back(fon->right);
                }
            }
            else
            {
                while(siz--)
                {
                    fon=d.back();
                    d.pop_back();
                    tmp.push_back(fon->val);
                    if(fon->right!=NULL)
                        d.push_front(fon->right);
                    if(fon->left!=NULL)
                        d.push_front(fon->left);
                }
            }
            ans.push_back(tmp);
        }
        return ans;
    }
};

你可能感兴趣的:(面试题,BFS,队列)