题目描述:
方法一;
class Solution(object):
def levelOrder(self, root): if not root:
return []
ans = []
stack = [root]
while stack:
tem_stack = []
tem_ans = []
for i in stack:
tem_ans.append(i.val)
if i.left:
tem_stack.append(i.left)
if i.right:
tem_stack.append(i.right)
stack = tem_stack
ans.append(tem_ans)
return ans
java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<> ();
if(root == null){
return ans;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> list = new ArrayList<>();
while(size > 0){
TreeNode curr = queue.poll();
list.add(curr.val);
size--;
if (curr.left != null){
queue.offer(curr.left);
}
if (curr.right != null){
queue.offer(curr.right);
}
}
ans.add(list);
}
return ans;
}
}