输出单层结点

题目:

对于一棵二叉树,请设计一个算法,创建含有某一深度上所有结点的链表。

给定二叉树的根结点指针TreeNode* root,以及链表上结点的深度,请返回一个链表ListNode,代表该深度上所有结点的值,请按树上从左往右的顺序链接,保证深度不超过树的高度,树上结点的值为非负整数且不超过100000。

思路:
每次往下一层,dep-1

# -*- coding:utf-8 -*-
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:
    l = ListNode(-1)
    p = l
    def getTreeLevel(self, root, dep):
        # write code here
        if not root or dep == 0:
            return
        if dep == 1:
            self.p.next = ListNode(root.val)
            self.p = self.p.next
        else:
            self.getTreeLevel(root.left,dep-1)
            self.getTreeLevel(root.right,dep-1)
        return self.l.next

if __name__ == '__main__':
    head = TreeNode(1)
    head.left = TreeNode(2)
    head.right = TreeNode(3)

    head.left.left = TreeNode(4)
    head.left.right = TreeNode(5)

    head.left.left.left = TreeNode(6)
    head.left.left.right = TreeNode(7)

    s = TreeLevel()
    s.getTreeLevel(head,2)
    print(s.l.next.val)


你可能感兴趣的:(输出单层结点)