题解 | #从上往下打印二叉树#

从上往下打印二叉树

http://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701

-- coding:utf-8 --

class TreeNode:

def init(self, x):

self.val = x

self.left = None

self.right = None

class Solution: # 返回从上到下每个节点值列表,例:[1,2,3] def PrintFromTopToBottom(self, root): # write code here if not root: return

    ret = []
    curLevel = []

    cur = root
    curLevel.append(root)

    while len(curLevel)>0:
        nextLevel = []
        for item in curLevel:
            ret.append(item.val)
            if item.left:
                nextLevel.append(item.left)
            if item.right:
                nextLevel.append(item.right)
        curLevel = nextLevel
    return ret
        
全部评论

相关推荐

牛客969571862号:昨天捞我今天面这个,岗位一模一样,感觉就是面着玩
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务