[LeetCode] 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).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
這題目其實是要求按層遍歷二叉樹,並且分層輸出。在遍歷二叉樹時最簡單就是遞歸了,但簡單遞歸無法保存層的信息,在藉助隊列遍歷時,也只能簡單的按層輸出,無法確

元素在那一層,這裏借鑑了別人的思想:設置兩個標記量分別標記parent數和child數,再說一次,要得到按層遍歷的序列不難,難的是怎麼確定什麼時候是分層,開始的

時候queue只有root一個元素,此時parentIndex = 1, childIndex = 0,由於它的left和right都爲飛空,所以root.left 和 root.right 分別入隊列,

childIndex 遞增兩次,即childIndex += 2。。。算了,我也說不清,還是上代碼吧:

class TreeNode:
	def __init__(self, x):
		self.val = x
		self.left = None
		self.right = None

class Solution:
	# @param root, a tree node
	# @param sum, an integer
	# @return a boolean
			
	def levelOrder(self, root):
		if None == root:
			return []
		queue = [root]
		ret = []
		tmp = []
		parentIndex = 1
		childIndex = 0
		while len(queue) > 0:
			leaf = queue[0]
			tmp.append(leaf.val)
			del queue[0]
			if None != leaf.left:
				queue.append(leaf.left)
				childIndex += 1
			if None != leaf.right:
				queue.append(leaf.right)
				childIndex += 1
			parentIndex -= 1

			if 0 == parentIndex:
				ret.append(tmp)
				tmp = []
				parentIndex = childIndex
				childIndex = 0
		return ret




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章