Topic link
The original title of https://leetcode.com/problems/binary-tree-level-order-traversal/
Given a binary tree, return to 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
/ 7
Return the order traversal as:
[
[3],
[9,20],
[15,7]
]
Title Translation
Given a binary tree, the sequence traversal results of all node values are returned. (from left to right, traversing from top to bottom)
For example, give a two-fork tree: {3,9,20,#,#,15,7},
3
/
9
/ 7
Its sequence traversal results are:
[
[3],
[9,20],
[15,7]
]
method of Thinking
idea of a
The general idea of sequence traversal is to do breadth-first traversal (BFS). Traversing the same time, note that the record traversal results to meet the requirements of the output format of the problem.
Code
# Definition for a binary tree node.
# class TreeNode (object):
# def __init__ (self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution (object):
def levelorder (self, Root): ""
: Type root: TreeNode
: Rtype:list[list[int]]
""
res = []
if root = = None: return
res
q = [Root] While
Len (q)!= 0:
res.append ([Node.val to node in Q])
new_q = [] for
node in Q:
if node.left:< C24/>new_q.append (node.left)
if node.right:
new_q.append (node.right)
q = new_q return
res
Idea two
With depth-first search (DFS), the depth of a node corresponds to the subscript of an array of output results. Note that you want to save the value of each access node at the time of recursion.
Code
# Definition for a binary tree node.
# class TreeNode (object):
# def __init__ (self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution (object):
def levelorder (self, Root): ""
: Type root: TreeNode
: Rtype:list[list[int]]
""
res = []
self.dfs (root, 0, res) return
res
def DFS (self, root, depth, res):
if root = = None: return
res
if Len (res) < depth+1:
res.append ([])
Res[depth].append (Root.val)
Self.dfs (Root.left, depth+1, res)
Self.dfs (Root.right, depth+1, RES)
PS: Novice Brush Leetcode, new handwritten blog, write wrong or write not clear also please help point out, thank you.
reprint Please specify: http://blog.csdn.net/coder_orz/article/details/51363095