题目
- 请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路
代码
import java.util.ArrayList;
import java.util.Stack;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> resultlist = new ArrayList<>();
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
boolean flag = true;
if(pRoot==null)
return resultlist;
stack1.push(pRoot);
while(!stack1.isEmpty()||!stack2.isEmpty()){
if(flag==true){
ArrayList<Integer> templist1 = new ArrayList<>();
while(!stack1.isEmpty()){
TreeNode temp = stack1.pop();
templist1.add(temp.val);
if(temp.left!=null){
stack2.push(temp.left);
}
if(temp.right!=null){
stack2.push(temp.right);
}
}
resultlist.add(templist1);
flag=false;
}else{
ArrayList<Integer> templist2 = new ArrayList<>();
while(!stack2.isEmpty()){
TreeNode temp = stack2.pop();
templist2.add(temp.val);
if(temp.left!=null){
stack1.push(temp.right);
}
if(temp.right!=null){
stack1.push(temp.left);
}
}
resultlist.add(templist2);
flag=true;
}
}
return resultlist;
}
}
链接:https://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0
来源:牛客网
ArrayList<ArrayList<Integer> > listAll = new ArrayList<>();
if(pRoot==null)return listAll;
Stack<TreeNode> s1 = new Stack<>();
Stack<TreeNode> s2 = new Stack<>();
int level = 1;
s1.push(pRoot);
while(!s1.isEmpty()||!s2.isEmpty()){
ArrayList<Integer> list = new ArrayList<>();
if(level++%2!=0){
while(!s1.isEmpty()){
TreeNode node = s1.pop();
list.add(node.val);
if(node.left!=null)s2.push(node.left);
if(node.right!=null)s2.push(node.right);
}
}
else{
while(!s2.isEmpty()){
TreeNode node = s2.pop();
list.add(node.val);
if(node.right!=null)s1.push(node.right);
if(node.left!=null)s1.push(node.left);
}
}
listAll.add(list);
}
return listAll;
链接:https://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0
来源:牛客网
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
if (pRoot == null)
{
return list;
}
Stack<TreeNode> stack1 = new Stack<TreeNode>();
Stack<TreeNode> stack2 = new Stack<TreeNode>();
stack1.push(pRoot);
while (stack1.size() != 0 || stack2.size() != 0)
{
if (stack1.size() != 0)
{
ArrayList<Integer> list2 = new ArrayList<Integer>();
while (stack1.size() != 0)
{
TreeNode t = stack1.pop();
list2.add(t.val);
if (t.left != null)
{
stack2.push(t.left);
}
if (t.right != null)
{
stack2.push(t.right);
}
}
list.add(list2);
} else
{
ArrayList<Integer> list2 = new ArrayList<Integer>();
while (stack2.size() != 0)
{
TreeNode t = stack2.pop();
list2.add(t.val);
if (t.right != null)
{
stack1.push(t.right);
}
if (t.left != null)
{
stack1.push(t.left);
}
}
list.add(list2);
}
}
return list;