题解 | 按之字形顺序打印二叉树

按之字形顺序打印二叉树

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
  public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> > res;
        if (!pRoot)
            return res;
        queue<TreeNode*> q; // 定义队列
        q.push(pRoot); // 根结点入队列
        int level = 0;
        while (!q.empty()) {
            vector<int> arr; // 定义数组存储每一行结果
            int size = q.size(); // 当前队列长度
            for (int i = 0; i < size; i++) {
                TreeNode* tmp = q.front(); // 队头元素
                q.pop();
                // if (!tmp) // 空元素跳过
                //     continue;
                // q.push(tmp->left); // 左孩子入队列
                // q.push(tmp->right); // 右孩子入队列
                 // 只在入队时检查,避免空节点进入队列
            if (tmp->left) 
                q.push(tmp->left);
            if (tmp->right)
                q.push(tmp->right);
                if (level % 2 == 0) {
                    // 从左至右打印
                    arr.push_back(tmp->val);
                } else { // 从右至左打印
                    arr.insert(arr.begin(), tmp->val);
                }
            }
            level++; // 下一层,改变打印方向
            // if (!arr.empty())
                res.push_back(arr); // 放入最终结果
        }
        return res;
    }
};

// if (!tmp) // 空元素跳过
//     continue;
// q.push(tmp->left); // 左孩子入队列
// q.push(tmp->right); // 右孩子入队列  
和 
// if (!arr.empty())配套使用

因为左右孩子可能为空,导致空指针进入队列

如果没有// if (!tmp) // 空元素跳过
       //     continue;
就可能导致空操作

如果没有// if (!arr.empty())配套使用
就会在结果后面多输出一个空数组

但更好的做法是从根本上避免产生空数组
改进方案:在入队时避免空节点
 if (tmp->left) 
      q.push(tmp->left);
if (tmp->right)
      q.push(tmp->right);

DS之二叉树 文章被收录于专栏

二叉树的遍历:前,中,后,层次 二叉树的存储结构:链式,顺序(主要用于完全二叉树) 二叉树的应用场景:二叉搜索树(BST),平衡二叉搜索树(AVL树、红黑树),堆,哈夫曼树,表达式树

全部评论

相关推荐

点赞 评论 收藏
分享
03-23 23:00
黄淮学院 Java
才浅Caiq:老家县城送外卖也5000,要求别这么低
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务