leetcode -- Binary Tree Level Order Traversal & II-- 重点

https://leetcode.com/problems/binary-tree-level-order-traversal/
https://leetcode.com/problems/binary-tree-level-order-traversal-ii/

这题目其实就是 BFS. 但是需要区分不同的level。通常的做法就是使用queue。这里因为每个node没有level的属性,于是我建立了一个level的queue,然后再bfs。

from collections import deque
class Solution(object):
    def levelOrder(self, root):
        """ :type root: TreeNode :rtype: List[List[int]] """
        if root == None:
            return []
        qnode = deque([root])
        qlevel = deque([0])
        res_all = []
        res = []
        curlevel = -1
        while len(qnode) > 0:
            node = qnode.popleft()
            #print (len(qnode), node)
            #print node
            prelevel = curlevel
            curlevel = qlevel.popleft()
            #print curlevel
            if curlevel > prelevel:
                if curlevel > 0:
                    res_all.append(res)
                res = []
            res.append(node.val)

            if node.left != None:
                qnode.append(node.left)
                qlevel.append(curlevel + 1)
            if node.right != None:
                qnode.append(node.right)
                qlevel.append(curlevel + 1)
        res_all.append(res)
        return res_all

其实这里可以更简洁一点,用dfs,即pre-order。把level算成参数,然后加上res。
http://www.cnblogs.com/zuoyuan/p/3722004.html

class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    def preorder(self, root, level, res):
        if root:
            if len(res) < level+1: res.append([])
            res[level].append(root.val)
            self.preorder(root.left, level+1, res)
            self.preorder(root.right, level+1, res)
    def levelOrder(self, root):
        res=[]
        self.preorder(root, 0, res)
        return res

你可能感兴趣的:(LeetCode)