按字形顺序打印二叉树

101 阅读1分钟

image.png 链接:www.nowcoder.com/practice/91…
思路:使用bfs去遍历树,将节点和节点深度存在queueNode中;再把每一行节点中的值存在nowVector中,换行时记得把nowVector清零。因为bfs遍历都是从左到右,层数时从0开始数,所以奇数层的nowVector需要反转后在存入result中,最后返回result中就可以了。\

这次因为最后一行没有 判断是否反转 的逻辑,错了2次。

class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {

        vector<vector<int> > result;
        int preDeepth = 0;
        if(pRoot == nullptr) return result;

        queue<pair<TreeNode*,int> > queueNode;
        queueNode.push({pRoot,0});

        pair<TreeNode*, int> nowNode;
        vector<int> nowVector;

        while(!queueNode.empty()) {
            nowNode = queueNode.front();
            queueNode.pop();
            cout<<preDeepth<<' '<<nowNode.first->val<<' '<<nowNode.second<<endl;
            if(nowNode.second != preDeepth)  {
                if(preDeepth&1) {
                    reverse(nowVector.begin(), nowVector.end());
                }
                result.push_back(nowVector);
                nowVector.clear();
                preDeepth = nowNode.second;
            }
            nowVector.push_back(nowNode.first->val);
            if(nowNode.first->left != nullptr) queueNode.push({nowNode.first->left,nowNode.second+1});
            if(nowNode.first->right != nullptr) queueNode.push({nowNode.first->right,nowNode.second+1});
        }
        if(preDeepth&1) {
            reverse(nowVector.begin(), nowVector.end());
        }
        result.push_back(nowVector);
        return result;
    }

};