剑指offer:(23)举例让抽象问题具体化 :从上往下打印二叉树
来源:互联网 发布:网络教育的在职研究生 编辑:程序博客网 时间:2024/06/07 21:59
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路: 二叉树的层次遍历么,借助一个队列就可以了
package co.com.jianzhioffer;import java.util.ArrayList;import java.util.LinkedList;import java.util.Queue;public class Solution23 {public static class TreeNode {int val = 0;TreeNode left = null;TreeNode right = null;public TreeNode(int val) {this.val = val;}}//循环/*static ArrayList<Integer> result = new ArrayList<Integer>();static Queue<TreeNode> que = new LinkedList<TreeNode>();public static ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {if (root == null)return null;result.add(root.val);if (root.left != null)que.add(root.left);if (root.right != null)que.add(root.right);if (!que.isEmpty()) {root = que.poll();PrintFromTopToBottom(root);}return result;}*/public static ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {ArrayList<Integer> list = new ArrayList<Integer>();if(root == null) return list; Queue<TreeNode> que = new LinkedList<TreeNode>();que.offer(root);while(!que.isEmpty()){TreeNode node = que.poll();list.add(node.val);if(node.left!=null) que.offer(node.left);if(node.right!=null) que.offer(node.right);}return list;}public static void main(String[] args) {TreeNode root = new TreeNode(1);root.left = new TreeNode(2);root.right = new TreeNode(3);root.left.left = new TreeNode(4);root.left.right = new TreeNode(5);ArrayList<Integer> res = PrintFromTopToBottom(root);System.out.println(res);}}
阅读全文
0 0
- 剑指offer:(23)举例让抽象问题具体化 :从上往下打印二叉树
- 剑指offer 23题 【举例让抽象具体化】从上往下打印二叉树
- 《剑指offer》刷题笔记(举例让抽象具体化):从上往下打印二叉树
- 【剑指offer】4.3举例让抽象问题具体化——面试题23:从上往下打印二叉树
- 剑指offer:(23)举例让抽象问题具体化 :二叉搜索树的后序遍历序列
- 剑指offer:(25)举例让抽象问题具体化 :二叉搜索树的后序遍历序列
- 剑指offer 23 - 从上往下打印二叉树
- 剑指Offer-23-从上往下打印二叉树
- 《剑指offer》:[23]从上往下打印二叉树
- 剑指Offer 23 从上往下打印二叉树
- 剑指offer 23 从上往下打印二叉树
- 剑指offer(24):从上往下打印二叉树
- 剑指offer(19)-从上往下打印二叉树
- 剑指offer面试题[23]-从上往下打印二叉树(按层序打印)
- 剑指offer 24题 【举例让抽象具体化】二叉搜索树的后序遍历序列
- 剑指offer 25题 【举例让抽象具体化】二叉树中和为某一值的路径
- 《剑指offer》刷题笔记(举例让抽象具体化):二叉搜索树的后序遍历序列
- 《剑指offer》刷题笔记(举例让抽象具体化):二叉树中和为某一值的路径
- Ambari 安装agent失败解决
- geoserver 通过代码实现发布地图服务
- mapping 映射
- 三维dem
- unity 安卓应用名称多语言本地化
- 剑指offer:(23)举例让抽象问题具体化 :从上往下打印二叉树
- geoserver中除了使用kml来查询数据以外,还可以使用csql或ecsql
- PM2管理nodejs
- Android Tv 焦点总结 TvRecyclerView
- linux 操作笔记
- mvn 使用
- eclipse
- html音乐播放js/jq
- 一些概念