题目:
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路:
利用层次遍历,奇数行进入list1,偶数行先进入栈,当栈大小等于队列之前统计的当前层的个数时,栈所有的依次出栈进入list2。
Java
package nowcoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class S59_ZPrint {
public ArrayList<ArrayList<Integer>> ZPrint(TreeNode root){
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
if (root == null)
return list;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
int layer = 1;//层数
int layerCount = 1;//当前层的个数
int count = 0;//计数
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()){
TreeNode out = queue.poll();
count++;
if (out.left != null){
queue.offer(out.left);
}
if (out.right != null){
queue.offer(out.right);
}
//奇数层
if (layer %2 == 1){
list1.add(out.val);
if (list1.size() == layerCount){
list.add(list1);
list1 = new ArrayList<Integer>();
}
}
else {
//偶数层先进栈
stack.push(out);
//若栈中的个数==layerCount,则弹出到list2
if (stack.size() == layerCount){
while (!stack.isEmpty())
list2.add(stack.pop().val);
list.add(list2);
list2 = new ArrayList<Integer>();
}
}
if (count == layerCount){
layer++;
layerCount = queue.size();
count = 0;
}
}
return list;
}
public static void main(String[] args){
S59_ZPrint s59 = new S59_ZPrint();
PrintTreeLayer p = new PrintTreeLayer();
Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
TreeNode root = p.arrayToTree(array, 0);
System.out.println(s59.ZPrint(root));
}
}
结果:
[[1], [3, 2], [4, 5, 6, 7], [11, 10, 9, 8]]
Python
import PrintTreeLayer
class ZPrint:
def Print(self, pRoot):
if not pRoot:
return []
nodeStack = [pRoot]
result = []
while nodeStack:
res = []
nextStack = []
for i in nodeStack:
res.append(i.val)
if i.left:
nextStack.append(i.left)
if i.right:
nextStack.append(i.right)
nodeStack = nextStack
result.append(res)
returnResult = []
for i, v in enumerate(result):
if i % 2 == 0:
returnResult.append(v)
else:
returnResult.append(v[::-1])
return returnResult
if __name__ == '__main__':
test = ZPrint()
p = PrintTreeLayer.PrintTreeLayer()
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
root = p.arrayToTree(array, 0)
print(test.Print(root))