从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路:利用队列层次遍历树
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
if(root == null)return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
TreeNode cur = queue.poll();
result.add(cur.val);
if(cur.left != null)
queue.add(cur.left);
if(cur.right != null)
queue.add(cur.right);
}
return result;
}
分行
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if(pRoot == null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
int toBePrinted = 1;//行内的节点数
int nextLevel = 0;//下一行节点数
ArrayList<Integer> list = new ArrayList<>();
while(!queue.isEmpty()) {
TreeNode cur = queue.poll();
list.add(cur.val);
toBePrinted--;
if(cur.left != null){
queue.add(cur.left);
nextLevel++;
}
if(cur.right != null){
queue.add(cur.right);
nextLevel++;
}
if(toBePrinted == 0){
result.add(list);
toBePrinted = nextLevel;
nextLevel = 0;
list = new ArrayList<>();
}
}
return result;
}
之字
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if(pRoot == null) return result;
Stack<TreeNode> cur_stack = new Stack<>(); //当前层的辅助栈
Stack<TreeNode> son_stack = new Stack<>(); //子层的辅助栈
int flag = 0;//0表示奇(从左到右),1表示偶(从右到左)
cur_stack.push(pRoot);
ArrayList<Integer> list = new ArrayList<>();
while(!cur_stack.isEmpty()) {
TreeNode cur = cur_stack.pop();
list.add(cur.val);
if(flag == 0) { //子节点从左到右(栈)
if(cur.left != null){
son_stack.push(cur.left);
}
if(cur.right != null){
son_stack.push(cur.right);
}
}else {
if(cur.right != null){
son_stack.push(cur.right);
}
if(cur.left != null){
son_stack.push(cur.left);
}
}
if(cur_stack.isEmpty()) {//这一层结束
result.add(list);
flag = flag == 0 ? 1 : 0;
cur_stack = son_stack;
son_stack = new Stack<>();
list = new ArrayList<>();
}
}
return result;
}