输出单层结点 牛客网 程序员面试金典 C++ Python
-
题目描述
-
对于一棵二叉树,请设计一个算法,创建含有某一深度上所有结点的链表。
-
给定二叉树的根结点指针TreeNode* root,以及链表上结点的深度,请返回一个链表ListNode,代表该深度上所有结点的值,请按树上从左往右的顺序链接,保证深度不超过树的高度,树上结点的值为非负整数且不超过100000。
C++
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class TreeLevel {
public:
//run:4ms memory:476k
ListNode* head = new ListNode(-1);
ListNode* p = head;
ListNode* getTreeLevel(TreeNode* root, int dep) {
if (NULL == root || dep <= 0) return NULL;
if (1 == dep){
ListNode* tmp = new ListNode(root->val);
p->next = tmp;
p = p->next;
}else{
getTreeLevel(root->left,dep - 1);
getTreeLevel(root->right,dep - 1);
}
return head->next;
}
Python
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class TreeLevel:
#run:51ms memory:5856k
head = ListNode(-1)
p = head
def getTreeLevel(self, root, dep):
if None == root: return None
if dep <= 0: return None
if dep == 1:
tmp = ListNode(root.val)
self.p.next = tmp
self.p = self.p.next
else:
self.getTreeLevel(root.left,dep-1)
self.getTreeLevel(root.right,dep-1)
return self.head.next