剑指offer——之字形打印二叉树(一般)
来源:互联网 发布:停车场收费系统数据库 编辑:程序博客网 时间:2024/06/05 17:02
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路:
一个LinkedList,用于存放每层的节点;一个Stack,用于在需要逆向顺序打印时,把LinkedList里的数据先放进Stack里,再从Stack里存到ArrayList。
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> result = new ArrayList<>(); if (pRoot == null) return result; LinkedList<TreeNode> container = new LinkedList<>(); Stack<TreeNode> stack = new Stack<>(); int m = 1; // 层数 int n = 1; // 每层的节点数 container.offer(pRoot); while (container.size() != 0) { ArrayList<Integer> list = new ArrayList(); while (n > 0) { TreeNode temp = container.poll(); if (m % 2 == 1) // 奇数层是从左往右打印,所以直接添加 list.add(temp.val); else // 偶数层的话先放进stack里 stack.push(temp); if (temp.left != null) container.offer(temp.left); if (temp.right != null) container.offer(temp.right); n--; } n = container.size(); if (m % 2 == 0) { while (!stack.isEmpty()) // 从stack输出到list,从右向左的顺序 list.add(stack.pop().val); } m++; result.add(list); } return result; }
剑指offer思路:
两个栈配合
public static ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { int layer = 1; //s1存奇数层节点 Stack<TreeNode> s1 = new Stack<TreeNode>(); s1.push(pRoot); //s2存偶数层节点 Stack<TreeNode> s2 = new Stack<TreeNode>(); ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); while (!s1.empty() || !s2.empty()) { if (layer%2 != 0) { ArrayList<Integer> temp = new ArrayList<Integer>(); while (!s1.empty()) { TreeNode node = s1.pop(); if(node != null) { temp.add(node.val); System.out.print(node.val + " "); s2.push(node.left); s2.push(node.right); } } if (!temp.isEmpty()) { list.add(temp); layer++; } } else { ArrayList<Integer> temp = new ArrayList<Integer>(); while (!s2.empty()) { TreeNode node = s2.pop(); if(node != null) { temp.add(node.val); System.out.print(node.val + " "); s1.push(node.right); s1.push(node.left); } } if (!temp.isEmpty()) { list.add(temp); layer++; } } } return list; }
阅读全文
0 0
- 剑指offer——之字形打印二叉树(一般)
- 《剑指offer》——按之字形顺序打印二叉树
- 剑指Offer——之字形打印二叉树
- 剑指offer——按之字形顺序打印二叉树
- 剑指offer——按之字形打印二叉树
- 剑指offer——按之字形顺序打印二叉树
- 剑指offer—按之字形顺序打印二叉树
- 剑指offer—按之字形顺序打印二叉树
- 剑指offer(C++)——按之字形顺序打印二叉树
- 剑指offer----之字形打印二叉树
- 剑指offer(62):之字形打印二叉树
- 剑指offer(56)-按之字形顺序打印二叉树
- java面试题(剑指offer):之字形打印二叉树
- 剑指offer——59.按之字形顺序打印二叉树
- 剑指offer——面试题61:按之字形顺序打印二叉树
- 剑指offer--按之字形顺序打印二叉树
- 剑指offer 61 - 按之字形打印二叉树
- 《剑指offer》按之字形顺序打印二叉树
- openCV 图像深度和通道介绍
- ZOJ 3305 Get Sauce
- python-3-print重定向输出的几种方法
- python之列表
- oracle 事物概述
- 剑指offer——之字形打印二叉树(一般)
- servlet 过滤器与监听器
- 仿百度新闻首页
- 非算法人员 暑假机器视觉之手势识别之路
- Qt单例模式
- deformable convolutional networks论文阅读理解
- [英]Haskell and Genetic Algorithm solving Sudoku
- 面向对象---继承顺序
- 机械硬盘(HDD)与固态硬盘(SSD)