[LeetCode] 102. Binary Tree Level Order Traversal 二叉树层序遍历

方法一:

    使用队列辅助,做二叉树的层序遍历,这里由于需要将每层的节点分开,需要在节点入队列的同时,记录节点的层次,

整是套用使用队列对二叉树做层次遍历的框架。代码如下:

/*
 * @Descripttion: 
 * @version: 
 * @Author: wangxf
 * @Date: 2020-07-06 23:39:37
 * @LastEditors: Do not edit
 * @LastEditTime: 2020-07-07 00:22:54
 */ 
/*
 * @lc app=leetcode.cn id=102 lang=cpp
 *
 * [102] 二叉树的层序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

struct NodeInfo
{
    TreeNode* ptr = nullptr;
    int level = 0;
    NodeInfo(TreeNode* node_ptr,int node_level):
    ptr(node_ptr),level(node_level)
    {}

};
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root)
    {
        
        std::vector<vector<int>> res;
        if(!root) return res;
        std::queue<NodeInfo> q;
        NodeInfo root_node(root,0);
        q.push(root_node);
        while(!q.empty())
        {
            NodeInfo cur_node = q.front();
            q.pop();
            int cur_level = cur_node.level;
            int cur_node_val = cur_node.ptr->val;
            if(res.size()<cur_level+1)
            {
                vector<int> tempVec;
                res.push_back(tempVec);
            }
            res[cur_level].push_back(cur_node_val);
            if(cur_node.ptr->left)
            {
               NodeInfo leftNode(cur_node.ptr->left,cur_level+1);
               q.push(leftNode);
            }
            if(cur_node.ptr->right)
            {
               NodeInfo rightNode(cur_node.ptr->right,cur_level+1);
               q.push(rightNode);
            }
        }
        return res;
    }
};
// @lc code=end

 

posted @ 2020-07-08 00:15  谁在写西加加  阅读(139)  评论(0编辑  收藏  举报