首页 > 代码库 > Binary Tree Level Order Traversal
Binary Tree Level Order Traversal
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。