输出单层结点
题目描述
对于一棵二叉树,请设计一个算法,创建含有某一深度上所有结点的链表。
给定二叉树的根结点指针TreeNode* root,以及链表上结点的深度,请返回一个链表ListNode,代表该深度上所有结点的值,请按树上从左往右的顺序链接,保证深度不超过树的高度,树上结点的值为非负整数且不超过100000。
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ /* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {} };*/ class TreeLevel { public: ListNode* getTreeLevel(TreeNode* root, int dep) { // write code here if(root == nullptr) return nullptr; queue<TreeNode*> Q,tmp; Q.push(root); int cnt = 1; ListNode *newList = new ListNode(0); ListNode *pNode = newList; while(!Q.empty()) { if(cnt==dep) { while(!Q.empty()) { ListNode *newNode = new ListNode(Q.front()->val); Q.pop(); pNode->next = newNode; pNode = pNode->next; } } while(!Q.empty()) { TreeNode *cur = Q.front(); Q.pop(); tmp.push(cur->left); tmp.push(cur->right); } while(!tmp.empty()) { Q.push(tmp.front()); tmp.pop(); } ++cnt; } return newList->next; } };