Binary Tree Level Order Traversal 解題報告
阿新 • • 發佈:2018-12-27
Binary Tree Level Order Traversal
Description
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
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]
]
實現思路
通過一個佇列維護每一層的節點,在某一層中,一次從佇列中取出節點,再將其葉子節點放進下一層佇列中,遍歷完當前層,再遍歷下一層,直到下一層的佇列全為空,則結束層次遍歷
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
if (root == null){
return ret;
}
LinkedList<TreeNode> list = new LinkedList<>();
list.add(root);
while(!list.isEmpty()){
ArrayList<Integer> oneRet = new ArrayList<>();
List<TreeNode> tempNodes = new ArrayList(list.subList(0, list.size()));
list.clear();
for(TreeNode node : tempNodes){
oneRet.add(node.val);
if(node.left != null){
list.add(node.left);
}
if(node.right != null){
list.add(node.right);
}
}
ret.add(oneRet);
}
return ret;
}
}