把二叉树打印成多行
把二叉树打印成多行
https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&&tqId=11213&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
先上自己的方法,很显然是比较笨的,但是也能AC,而且效率还行:
import java.util.*;
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode root) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
if (root == null)
return ret;
Queue<TreeNode> q1 = new LinkedList<>();
Queue<Integer> q2 = new LinkedList<>();
ArrayList<Integer> last = new ArrayList<>();
ret.add(last);
q1.offer(root);
q2.offer(-1); // 遇到行末节点,就在q2中放-1
int val;
while (!q1.isEmpty()) {
root = q1.poll();
val = q2.poll();
last = ret.get(ret.size() - 1);
last.add(root.val);
if (val != -1) {
if (root.left != null) {
q1.offer(root.left);
q2.offer(1);
}
if (root.right != null) {
q1.offer(root.right);
q2.offer(1);
}
} else {
if (root.left != null || root.right != null) {
last = new ArrayList<>();
ret.add(last);
if (root.left != null) {
q1.offer(root.left);
if (root.right != null) {
q2.offer(1);
q1.offer(root.right);
q2.offer(-1);
} else {
q2.offer(-1);
}
} else {
if (root.right != null) {
q1.offer(root.right);
q2.offer(-1);
}
}
}
}
}
return ret;
}
} 再看题解的解法:
import java.util.*;
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode root) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if(root == null)
return res;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()) {
int size = q.size(); // 记录当前层有多少个元素
ArrayList<Integer> list = new ArrayList<>(size);
for(int i = 0; i < size; i++) {
root = q.poll();
list.add(root.val);
if(root.left != null)
q.add(root.left);
if(root.right != null)
q.add(root.right);
}
res.add(list);
}
return res;
}
} 也是非常直观的,巧妙就在于记录下每层的元素个数,然后多次出队把当前层的全部出队,对当前层遍历后,再将这一层的全部子节点入队,依次类推。
