给定一个二叉树,返回其按层次遍历的节点值。 (即zhu‘ceng‘de,从左到右访问)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果为:
[
[3],
[9,20],
[15,7]
]
详见:https://leetcode.com/problems/binary-tree-level-order-traversal/description/
/** * 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*> que; que.push(root); vector<int> out; int i=1; while(!que.empty()) { root=que.front(); que.pop(); --i; out.push_back(root->val); if(root->left) { que.push(root->left); } if(root->right) { que.push(root->right); } if(i==0) { i=que.size(); res.push_back(out); out.clear(); } } return res; } };
原文地址:https://www.cnblogs.com/xidian2014/p/8718154.html
时间: 2024-12-28 10:09:09