很明显使用的广度优先的方法,需要注意的就是广度实现本身。
另外实现的过程中暴露了链表建立的问题:需要两个节点变量来生成链表,仅一个节点(仅对我而言)无法实现连接与数值的更新。
由于前文树的遍历提到了这种方法,这里不再详述直接贴代码:
/*
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:
void levelorder (TreeNode *root, int dep, ListNode *pHead)
{
int d = 1, count = 0, num = 0, threshold = 1;
ListNode *start = pHead;
bool first = true;
queue<TreeNode *> q;
q.push(root);
while(!q.empty())
{
TreeNode *temp = q.front();
q.pop();
count ++;
if (d == dep)
{
ListNode *t = new ListNode(temp->val);
if (first) // 第一次初始化
{
first = false;
start->next = t->next;
start->val = t->val;
}
else
{
start->next = t;
start = start->next;
}
}
if (temp->left)
{
q.push(temp->left);
num ++;
}
if (temp->right)
{
q.push(temp->right);
num ++;
}
if (threshold == count)
{
d ++;
if (d > dep)
break;
threshold = num;
num = 0;
count = 0;
}
//count ++;
}
}
ListNode* getTreeLevel(TreeNode* root, int dep)
{
// write code here
if (!root) return NULL;
if (dep < 0) return NULL;
ListNode *pHead = new ListNode(-100);
levelorder(root, dep, pHead);
return pHead;
}
};