剑指Offer 面试题32 - II. 从上到下打印二叉树 II

面试题32 - II. 从上到下打印二叉树 II

解题思路:

BFS从根节点开始遍历二叉树,如何判断当前是哪一层呢?利用tag打标记,第一次的end_node设置为root ,后面记录下一层的最后一个节点,用tag存储,当前层的最后一个节点进入队列的时候,将当前的vector压入结果中,清空vector并更新end_node的值。

源代码:
/**
 * 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 {
private:
    queue<TreeNode *> que;
    int number[100][1002] = {-1};
public:
    // 典型的bfs应用
    vector<vector<int>> levelOrder(TreeNode* root) {
        int level = 0;
        vector<vector<int>> res;
        vector<int> tmp;
        if(!root) return res;
        que.push(root);
        TreeNode *end_node = root, *c_node = root, *tag = end_node;
        while(!que.empty()){
            tmp.push_back(c_node->val);
            que.pop();
            if(c_node->left){
                que.push(c_node->left);
                tag = c_node->left;
            }
            if(c_node->right){
                que.push(c_node->right);
                tag = c_node->right;
            }
            // 当前层已经结束,更新end_node的值
            if(c_node == end_node){
                end_node = tag;
                res.push_back(tmp);
                tmp.clear();
                level ++;
            }
            c_node = que.front();
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值