c++实现---之字形打印二叉树

题目:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
与之前的打印二叉树都是特别像,因此是同样的思路解决,使用bfs借助队列很方便的可以解决。
首先回顾一下模板:
如果不需要确定当前遍历到了哪一层,模板如下:

void bfs() {
 vis[] = {0}; // or set
 queue<int> pq(start_val);

 while (!pq.empty()) {
     int cur = pq.front(); pq.pop();
     for (遍历cur所有的相邻节点nex) {
         if (nex节点有效 && vis[nex]==0){
             vis[nex] = 1;
             pq.push(nex)
         }
     } // end for
 } // end while
}

如果需要确定遍历到哪一层,模板如下:

void bfs() {
 int level = 0;
 vis[] = {0}; // or set
 queue<int> pq(original_val);
 while (!pq.empty()) {
     int sz = pq.size();

     while (sz--) {
             int cur = pq.front(); pq.pop();
         for (遍历cur所有的相邻节点nex) {
             if (nex节点有效 && vis[nex] == 0) {
                 vis[nex] = 1;
                 pq.push(nex)
             }
         } // end for
     } // end inner while
     level++;

 } // end outer while
}

这道题关键思路是奇数层从左往右,偶数层从右往左遍历;
代码如下:

class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int>> res;
        if(!pRoot){
            return res;
        }
        queue<TreeNode*> help;
        help.push(pRoot);
        int level=0;
        while(!help.empty()){
            int sz=help.size();
            vector<int> ans;
            while(sz--){
                 TreeNode *node=help.front();
                 help.pop();
                ans.push_back(node->val);
                if(node->left) help.push(node->left);
                if(node->right) help.push(node->right);
            }
            ++level;
            if(!(level&1)){//使用位运算快速判断一个数是偶数还是奇数
                reverse(ans.begin(), ans.end());//如果是偶数层则反转vector
            }
            res.push_back(ans);
        }
        return res;
    }
    
};

猜你喜欢

转载自blog.csdn.net/Fizz6018/article/details/106933282
今日推荐