[leetcode]102. Binary Tree Level Order Traversal

[leetcode]102. Binary Tree Level Order Traversal


Analysis

ummmmmm—— [每天刷题并不难0.0]

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
在这里插入图片描述
二叉树的层序遍历~

Implement

/**
 * 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 {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res; 
        if(!root)
            return res;
        queue<TreeNode*> node;
        node.push(root);
        while(!node.empty()){
            vector<int> val1;
            int cnt = node.size();
            for(int i=0; i<cnt; i++){
                TreeNode* tmp = node.front();
                node.pop();
                val1.push_back(tmp->val);
                if(tmp->left)
                    node.push(tmp->left);
                if(tmp->right)
                    node.push(tmp->right);
            }
            res.push_back(val1);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/83475327