class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> reslist = new ArrayList<>();
if (pRoot == null) return reslist;
Stack<TreeNode> nodeStack1 = new Stack<>();
Stack<TreeNode> nodeStack2 = new Stack<>();
nodeStack1.push(pRoot);
boolean isleft = true;
ArrayList<Integer> tmplist = new ArrayList<>();
while (!nodeStack1.isEmpty()) {
TreeNode tmpnode = nodeStack1.pop();
tmplist.add(tmpnode.val);
if (isleft) {
if (tmpnode.left != null) {
nodeStack2.push(tmpnode.left);
}
if (tmpnode.right != null) {
nodeStack2.push(tmpnode.right);
}
} else {
if (tmpnode.right != null) {
nodeStack2.push(tmpnode.right);
}
if (tmpnode.left != null) {
nodeStack2.push(tmpnode.left);
}
}
if (nodeStack1.isEmpty()) {
reslist.add(tmplist);
tmplist= new ArrayList<>();
nodeStack1 = nodeStack2;
nodeStack2=new Stack<>();
isleft=!isleft;
}
}
return reslist;
}
之字型打印二叉树
最新推荐文章于 2024-02-18 10:31:45 发布