码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Level Order Traversal

时间:2014-11-19 08:33:46      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:des   blog   http   io   ar   on   div   log   ad   

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

 

Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).

 

Solutions:

1. DFS

In fact, tree PreOrder() is Level order Traversal. Just add the level number.

class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    def levelOrder(self, root):
        if not root: return []
        def PreOrder(root,level):
             
            if root:
                if level>=len(res):
                    res.append([])
                res[level].append(root.getRootVal())
                PreOrder(root.getLeftChild(),level+1)
                PreOrder(root.getRightChild(),level+1)
             
        res=[]
        PreOrder(root,0)
        return res

 

2.BFS

Exactly BFS. Note: BFS of tree is much simpler than that of Graph. No need to use visited array.

class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    def levelOrder(self, root):
        if not root: return []
        def PreOrder(root,level):
            
            if root:
                if level>=len(res):
                    res.append([])
                res[level].append(root.getRootVal())
                PreOrder(root.getLeftChild(),level+1)
                PreOrder(root.getRightChild(),level+1)
            
        res=[]
        PreOrder(root,0)
        return res

Binary Tree Level Order Traversal

标签:des   blog   http   io   ar   on   div   log   ad   

原文地址:http://www.cnblogs.com/idiotFRY/p/4107351.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!