题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> Print (TreeNode pRoot) {
if(pRoot == null) {
return new ArrayList<>();
}
// 方向
int direction = 0;
List<TreeNode> head = Arrays.asList(pRoot);
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
return executePrint(head, direction, result);
}
private ArrayList<ArrayList<Integer>> executePrint(List<TreeNode> head, int direction,
ArrayList<ArrayList<Integer>> result) {
ArrayList<Integer> list = new ArrayList<>();
if (head.size() == 0) {
return result;
}
if(direction == 0) {
// 正方向
for (TreeNode treeNode : head) {
list.add(treeNode.val);
}
List<TreeNode> children = getChildList(head);
result.add(list);
executePrint(children, (direction+1)%2, result);
}else {
// 反方向
List<TreeNode> children = getChildList(head);
// head转方向
Collections.reverse(head);
for (TreeNode treeNode : head) {
// 只是需要转完方向后的值而已
list.add(treeNode.val);
}
result.add(list);
executePrint(children, (direction+1)%2, result);
}
return result;
}
private List<TreeNode> getChildList(List<TreeNode> head) {
if(head.size() == 0)
return new ArrayList<>();
List<TreeNode > nodes = new ArrayList<>();
for (TreeNode treeNode : head) {
if(treeNode.left!= null) {
nodes.add(treeNode.left);
}
if(treeNode.right!= null) {
nodes.add(treeNode.right);
}
}
return nodes;
}
}
查看13道真题和解析