1.层序打印
- 借助队列先进先出的性质
- 先把root推入队列,进入♻️
- 当队列中有值时,推出该列队首的叶子节点,打印,并将该叶子节点的左右节点分别推出队列中,由于队列先进先出的性质,可以保证后推出的叶子节点一定晚于之前推入的上一个节点的值的打印顺讯。
/*
层序遍历树
*/
public void printTree(TreeNode root){
Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
while (!queue.isEmpty()){
TreeNode toBePrinted = queue.remove();
System.out.print(toBePrinted.val);
if (toBePrinted.left!=null){
queue.add(toBePrinted.left);
}
if (toBePrinted.right!=null){
queue.add(toBePrinted.right);
}
}
}
2.分行打印
- 定义一个levelNum来判断一行是否已经打印完毕;
- 每次打印完一行,也就证明遍历完一行的子节点,此时队列中的节点数量就是下一行要打印的节点数了;
/*
分行层序遍历树
*/
public void printTree2(TreeNode root){
Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
int levelNum = 1 ;
while (!queue.isEmpty()){
TreeNode toBePrinted = queue.remove();
System.out.print(toBePrinted.val);
levelNum --;
if (toBePrinted.left!=null){
queue.add(toBePrinted.left);
}
if (toBePrinted.right!=null){
queue.add(toBePrinted.right);
}
if (levelNum == 0 ) {
System.out.println();
levelNum = queue.size();
}
}
}
递归实现
链接:https://www.nowcoder.com/questionTerminal/445c44d982d04483b04a54f298796288
来源:牛客网
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
depth(pRoot, 1, list);
return list;
}
private void depth(TreeNode root, int depth, ArrayList<ArrayList<Integer>> list) {
if(root == null) return;
if(depth > list.size())
list.add(new ArrayList<Integer>());
list.get(depth -1).add(root.val);
depth(root.left, depth + 1, list);
depth(root.right, depth + 1, list);
}
3.Z字型打印二叉树
遇到奇数行要从左往右,遇到偶数行要从右往左,所以靠一种数据结构存储方式解决这个问题是很困难的,所以需要靠两个栈交替合作解决。
先将根节点存入一个栈。
- 进入循环
- 当某一个栈为空时,另一个栈一定不为空,此时将此栈中的节点一一弹出;每弹出一个节点,就将此节点的左右叶子节点推入另一个栈,直到此栈为空[一行遍历结束];将该行弹出节点存入res
- 当两栈都为空时,推出循环,此时已经将次二叉树遍历完全。
public ArrayList<ArrayList<Integer> > ZPrint(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
if (pRoot == null){
return res;
}
stack1.push(pRoot);
while (!stack1.isEmpty()||!stack2.isEmpty()){
ArrayList<Integer> templist = new ArrayList<>();
if (stack1.isEmpty()){
while (!stack2.isEmpty()){
TreeNode temp = stack2.pop();
templist.add(temp.val);
if (temp.right!=null){
stack1.push(temp.right);
}
if (temp.left!=null){
stack1.push(temp.left);
}
}
res.add(new ArrayList<>(templist));
}else {
while (!stack1.isEmpty()){
TreeNode temp = stack1.pop();
templist.add(temp.val);
if (temp.left!=null){
stack2.push(temp.left);
}
if (temp.right!=null){
stack2.push(temp.right);
}
}
res.add(new ArrayList<>(templist));
}
}
return res;
}