标签:order node init def treenode turn 节点 col root
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> levelOrder(TreeNode* root) { 13 vector<vector<int>> vec; 14 if(!root) return vec; 15 queue<TreeNode*> q; 16 q.push(root); 17 while(!q.empty()) 18 { 19 vector<int> tmp; 20 int len=q.size(); 21 for(int i=0;i<len;i++) 22 { 23 TreeNode* front=q.front(); 24 tmp.push_back(front->val); 25 q.pop(); 26 if(front->left) q.push(front->left); 27 if(front->right) q.push(front->right); 28 } 29 vec.push_back(tmp); 30 } 31 return vec; 32 } 33 };
标签:order node init def treenode turn 节点 col root
原文地址:https://www.cnblogs.com/cs0915/p/12881233.html