已知二叉树的根结点指针TreeNode* root以及链表上结点的深度,请设计算法返回一个链表ListNode,该链表代表该深度上所有结点的值,并按树上从左往右的顺序链接,深度不能超过树的高度,且树上结点的值为不大于100000的非负整数。
class TreeLevel:
def getTreeLevel(self, root, dep):
if not root: return
nodeStack = [root]
res = []
while nodeStack:
res.append([i.val for i in nodeStack])
nodeStack = [i for node in nodeStack for i in (node.left, node.right) if i]
dummy = ListNode(0)
pre = dummy
for i in res[dep - 1]:
node = ListNode(i)
pre.next = node
pre = pre.next
return dummy.next
def getTreeLevel(self, root, dep): if not root: return None queue = [] queue.append((1, root)) head = p = ListNode(-1) while queue: top = queue.pop(0) if top[0] == dep: node = ListNode(top[1].val) p.next = node p = p.next else: if top[1].left: queue.append((top[0] + 1, top[1].left)) if top[1].right: queue.append((top[0] + 1, top[1].right)) return head.next