题目:
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 root==None:
return result
deque=[]
deque.append(root)
while len(deque)!=0:
layer_number=len(deque)
temp=[]
for i in xrange(layer_number):
if deque[0].left!=None:
deque.append(deque[0].left)
if deque[0].right!=None:
deque.append(deque[0].right)
temp.append(deque.pop(0).val)
result.append(temp)
return result
c++代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <queue>
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
if(!root)
return result;
queue<TreeNode*> _queue;
_queue.push(root);
while(!_queue.empty())
{ int _len=_queue.size();
vector<int> tmp;
for (int i=0;i<_len;i++)
{
if (_queue.front()->left)
_queue.push(_queue.front()->left);
if(_queue.front()->right)
_queue.push(_queue.front()->right);
tmp.push_back(_queue.front()->val);
_queue.pop();
}
result.push_back(tmp);
}
return result;
}
};
如果不要求按层返回而是直接返回一个一维列表,则将代码改为
# 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 root==None:
return result
deque=[]
deque.append(root)
while len(deque)!=0:
if deque[0].left!=None:
deque.append(deque[0].left)
if deque[0].right!=None:
deque.append(deque[0].right)
result.append(deque.pop(0).val)
return result
总结:
对于二叉树,层序遍历用队列实现,其他遍历的非递归实现用栈实现(后续看一下)。