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,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
解题思路: 层次遍历二叉树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<List<Integer>> res;
public List<List<Integer>> levelOrder(TreeNode root) {
res = new ArrayList<List<Integer>>();
List<TreeNode> node = new ArrayList<TreeNode>();
if(root != null && node.add(root))
levelValue(node);
return res;
}
public void levelValue(List<TreeNode> node){
TreeNode tn;
List<Integer> value = new ArrayList<Integer>();
List<TreeNode> temp = new ArrayList<TreeNode>();
if(node.size() == 0)
return ;
for(int i = 0; i < node.size(); i++){
tn = node.get(i);
value.add(tn.val);
if(tn.left != null && temp.add(tn.left));
if(tn.right != null && temp.add(tn.right));
}
res.add(value);
levelValue(temp);
}
}
Note:
LeetCode上有一种1ms的解法,我想不出来也没搜到,谁有解法私聊我,谢谢!