程序员面试金典——4.4输出单层结点

#程序员面试金典——4.4输出单层结点

Solution1：我的答案

/*
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
//利用栈进行层次遍历
struct ListNode* result = NULL;
if(root == NULL || dep <= 0)
return result;
queue<TreeNode*> seq_tree;
vector<int> dupli;
seq_tree.push(root);
int cur = 1, next = 0, count_depth = 1;
struct TreeNode* temp = NULL;
while(!seq_tree.empty()) {
if(count_depth == dep + 1)
break;
temp = seq_tree.front();
if(count_depth == dep) {
dupli.push_back(temp->val);
}
cur--;
if(temp->left != NULL) {
seq_tree.push(temp->left);
next++;
}
if(temp->right != NULL) {
seq_tree.push(temp->right);
next++;
}
if(cur == 0) {
cur = next;
next = 0;
count_depth++;
}
seq_tree.pop();
}
return BuildList(dupli);
}
struct ListNode* BuildList(const vector<int> &res) {
struct ListNode* pHead = new ListNode(-1);
for(int i = 0; i < res.size(); i++) {
temp->next = new ListNode(res[i]);
temp = temp->next;
}
}
};


Solution2:递归遍历

/*
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
ListNode* list = new ListNode(-1);
get1(root,list,dep);
}
void get1(TreeNode* root, ListNode* &list, int dep) {
if (dep <= 0 || root == NULL)
return;
if (dep == 1) {
ListNode* listnext = new ListNode(root->val);
list->next = listnext;
list = list->next;
return ;
}
get1(root->left, list, dep - 1);
get1(root->right, list, dep - 1);
}
};


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120