Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
給定一個(gè)二叉樹(shù)滴某,返回他的水平層序遍歷(從左到右滋迈,一層再一層)
一個(gè)對(duì)隊(duì)列的巧妙應(yīng)用
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] ]
My Solution
(Java) Version 1 Time: 3ms:
隊(duì)列這個(gè)結(jié)構(gòu)就巧妙地把二叉樹(shù)的立體結(jié)構(gòu)變成線(xiàn)性結(jié)構(gòu)了另玖,也是一種巧妙地遍歷方式,先遍歷每個(gè)小樹(shù)的根結(jié)點(diǎn)敏释,然后把所有子節(jié)點(diǎn)都放進(jìn)隊(duì)列中晤硕,然后對(duì)隊(duì)列進(jìn)行遍歷舞箍,用size這個(gè)變量來(lái)保證每次都剛好遍歷了一層,知道隊(duì)列中沒(méi)有元素了疏橄,就表示樹(shù)沒(méi)有再發(fā)現(xiàn)新的子節(jié)點(diǎn)略就,于是結(jié)束遍歷
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null){
return new ArrayList<List<Integer>>();
}
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> first = new ArrayList<Integer>();
first.add(root.val);
result.add(first);
ArrayDeque<TreeNode> ad = new ArrayDeque<TreeNode>();
ad.add(root);
while(ad.size()!=0){
int size = ad.size();
List<Integer> temp = new ArrayList<Integer>();
for(int i = 0;i < size;i++){
TreeNode node = ad.removeFirst();
if(node.left!=null){
ad.add(node.left);
temp.add(node.left.val);
}
if(node.right!=null){
ad.add(node.right);
temp.add(node.right.val);
}
}
if(!temp.isEmpty())
result.add(temp);
}
return result;
}
}