《程式員面試金典》輸出單層結點,程式員面試金典
【 聲明:著作權,轉載請標明出處,請勿用於商業用途。 聯絡信箱:libin493073668@sina.com】
題目連結:http://www.nowcoder.com/practice/cb6c883b123b44399377d0c71e6ba3ea?rp=1&ru=/ta/cracking-the-coding-interview&qru=/ta/cracking-the-coding-interview/question-ranking
題目描述
對於一棵二叉樹,請設計一個演算法,建立含有某一深度上所有結點的鏈表。
給定二叉樹的根結點指標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 hereif(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;}};
著作權聲明:本文為博主原創文章,如果轉載,請註明出處