
这题也是层次遍历,很简单。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<ListNode*> res;
vector<TreeNode*> a,b;
ListNode* p,*q;
vector<ListNode*> listOfDepth(TreeNode* tree) {
a.push_back(tree);
int i;
while(a.size()!=0){
for(i=0;i<a.size();i++){
if(a[i]->left!=NULL){
b.push_back(a[i]->left);
}
if(a[i]->right!=NULL){
b.push_back(a[i]->right);
}
p=(ListNode*)new ListNode(a[i]->val);
if(i==0){
res.push_back(p);
}else{
q->next=p;
}
q=p;
}
a.clear();
a=b;
b.clear();
}
return res;
}
};
原文:https://www.cnblogs.com/hyffff/p/13747242.html