검지offer 면접문제 60 두 갈래 트리를 여러 줄로 인쇄(Java 구현)
1166 단어 검지offer 면접문제
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class Solution {
ArrayList> Print(TreeNode pRoot) {
ArrayList> arrayList = new ArrayList>();
if (pRoot == null) {
return arrayList;
}
Queue queue = new LinkedList();
queue.add(pRoot);
ArrayList arrayListlayer = new ArrayList<>();
int start = 0;
int end = 1;
while (!queue.isEmpty()) {
TreeNode cur = queue.remove();
arrayListlayer.add(cur.val);
start++;
TreeNode left = cur.left;
TreeNode right = cur.right;
if (left != null) {
queue.add(left);
}
if (right != null) {
queue.add(right);
}
if (start == end) {
end = queue.size();
start = 0;
arrayList.add(arrayListlayer);
arrayListlayer = new ArrayList<>();
}
}
return arrayList;
}
}