从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int[] levelOrder(TreeNode root) {
Queue<TreeNode> q = new LinkedList<TreeNode>();
ArrayList<Integer> l = new ArrayList<Integer>();
if(root!=null)q.add(root);
while(!q.isEmpty()){
root=q.poll();
l.add(root.val);
if(root.left!=null) q.add(root.left);
if(root.right!=null) q.add(root.right);
}
// 1.循环赋值int数组
int[] ans = new int[l.size()];
int i = 0;
for(Integer x : l) ans[i++] = x;
return ans;
// 2. 用流式处理,不知道为啥但是时间复杂度不如第一个,差很多!
//Integer[] ans = (Integer[]) l.toArray(new Integer[size]);
//return l.stream().mapToInt(Integer::valueOf).toArray();
}
}
剑指 Offer 32 - II. 从上到下打印二叉树 II
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
/**
* 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) {
Queue<TreeNode> q = new LinkedList<TreeNode>();
Queue<TreeNode> q_1 = new LinkedList<TreeNode>();
ArrayList<Integer> l = new ArrayList<Integer>();
List<List<Integer>> ans = new ArrayList<List<Integer>>();
if(root!=null)q.add(root);
while(!q.isEmpty()||!q_1.isEmpty()){
if(q.isEmpty()){
q=q_1;
q_1=new LinkedList<TreeNode>();;
ans.add(l);
l = new ArrayList<Integer>();;
continue;
}
root=q.poll();
l.add(root.val);
if(root.left!=null) q_1.add(root.left);
if(root.right!=null) q_1.add(root.right);
}
if(!l.isEmpty())ans.add(l);
return ans;
}
}
剑指 Offer 32 - III. 从上到下打印二叉树 III
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
/**
* 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) {
Stack<TreeNode> q = new Stack<TreeNode>();
Stack<TreeNode> q_1 = new Stack<TreeNode>();
ArrayList<Integer> l = new ArrayList<Integer>();
List<List<Integer>> ans = new ArrayList<List<Integer>>();
if(root!=null)q.add(root);
int high = 0;
while(!q.isEmpty()||!q_1.isEmpty()){
if(q.isEmpty()){
q=q_1;
q_1=new Stack<TreeNode>();
ans.add(l);
l = new ArrayList<Integer>();
high++;
continue;
}
root=q.pop();
l.add(root.val);
if(high%2==0){
if(root.left!=null) q_1.add(root.left);
if(root.right!=null) q_1.add(root.right);
}else{
if(root.right!=null) q_1.add(root.right);
if(root.left!=null) q_1.add(root.left);
}
}
if(!l.isEmpty())ans.add(l);
return ans;
}
}