剑指Offer LevelTraversalTree 层序遍历二叉树
来源:互联网 发布:球球大作战圣衣软件 编辑:程序博客网 时间:2024/06/06 17:23
题目描述:
从上往下打印二叉树的每个结点,同一层的结点按照从左到右的顺序打印。
思路:
1.循环+队列 每次扫描本层的所有节点放入队列 再从队头读取一个节点继续遍历子节点
public static void printByLoop(BinaryTreeNode root) { Queue<BinaryTreeNode> queue = new LinkedBlockingQueue<>(); if (root == null) {//如果二叉树为空 return; } while (root != null) { System.out.print(root.value + " "); if (root.leftNode != null) { queue.add(root.leftNode); } if (root.rightNode != null) { queue.add(root.rightNode); } root = queue.poll(); } }
2.递归实现 必须先计算出树的高度 再打印每层的节点
public static void printByRecursion(BinaryTreeNode root) { if (root == null) { return; } int dep = depth(root); for (int i = 1; i <=dep; i++) { print(root, i); } } private static void print(BinaryTreeNode root, int level) { if (root == null || level < 1) { return; } if (level == 1) { System.out.print(root.value + " "); } print(root.leftNode, level - 1); print(root.rightNode, level - 1); } private static int depth(BinaryTreeNode root) { if (root == null) { return 0; } //计算左右子树的高度 int left = depth(root.leftNode); int right = depth(root.rightNode); if (left > right) { return left + 1; } else { return right + 1; } }
阅读全文
0 0
- 剑指Offer LevelTraversalTree 层序遍历二叉树
- 剑指Offer--层序遍历二叉树
- 剑指 offer:从上到下打印二叉树(层序遍历)
- 剑指offer 面试题23 按层遍历二叉树
- 剑指offer 23----二叉树的前序、中序、后序、层序遍历
- 剑指Offer-->从上向下打印二叉树(层序遍历 + 详解)
- 剑指Offer----面试题23:从上往下打印二叉树(层序遍历)
- 剑指Offer------从上往下打印二叉树(层序遍历)
- 剑指Offer------把二叉树打印成多行(层序遍历)
- 剑指offer:从上往下打印二叉树(层遍历二叉树)
- 层序遍历二叉树
- 层序遍历二叉树
- 层序遍历二叉树
- 层序遍历二叉树
- 二叉树-层序遍历
- 二叉树------层序遍历
- 层序遍历二叉树
- 层序遍历二叉树
- 动手实操 | 如何用 Python 实现人脸识别
- 智能家居系统中网关与服务器如何连接?
- SVN项目迁移Gitlab实例版
- iOS开发,修改项目名称
- iOS开发入门笔记
- 剑指Offer LevelTraversalTree 层序遍历二叉树
- C#之集合概述
- Tomcat 访问过程
- JavaScript入门(二)
- python中decode和encode的区别和联系
- textview显示HTML中img的图片
- hdu 2821
- 断言(assert)表达式的使用
- 近似回文串、最长回文子串