1. 程式人生 > >[leetcode]102. Binary Tree Level Order Traversal

[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; } };