本文主要是介绍算法题:按之字形打印二叉树,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推
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>> list = new ArrayList();if(pRoot == null) {return list;}Stack<TreeNode> stack1 = new Stack();Stack<TreeNode> stack2 = new Stack();stack1.push(pRoot);while(!stack1.isEmpty() || !stack2.isEmpty()) {ArrayList<Integer> layer = new ArrayList();if(!stack1.isEmpty()) {while(!stack1.isEmpty()) {TreeNode root = stack1.pop();layer.add(root.val);if(root.left != null) stack2.push(root.left);if(root.right != null) stack2.push(root.right);}}else if(!stack2.isEmpty()) {while(!stack2.isEmpty()) {TreeNode root = stack2.pop();layer.add(root.val);if(root.right != null) stack1.push(root.right);if(root.left != null) stack1.push(root.left);}}list.add(layer);}return list;}
}
这篇关于算法题:按之字形打印二叉树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!