题目
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,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
python 答案
# 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]]
"""
result = []
if not root:
return result
queue = [root]
while queue:
new_q = []
result.append([x.val for x in queue])
for node in queue:
if node.left:
new_q.append(node.left)
if node.right:
new_q.append(node.right)
queue = new_q
return result
js答案
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
var result =[],queue = [];
if(!root){
return result
}
queue.push(root);
while(queue.length > 0){
var currentLevel = [ ];
//current
var size = queue.length;
for(var i = 0; i<size; i++){
var element = queue.shift();
currentLevel.push(element.val)
if(element.left){
queue.push(element.left)
}
if(element.right){
queue.push(element.right)
}
}
result.push(currentLevel)
}
return result
};
网友评论