算法从下到上打印二叉树
Posted Kant101
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法从下到上打印二叉树相关的知识,希望对你有一定的参考价值。
1. 概述
从下到上打印二叉树属于树的遍历的改编。
2. 分析
这个问题是树的层次遍历的变种,我们可以首先通过从上到下的层次遍历得到遍历的结果,然后翻转得到从下到上的遍历结果,即为最终的结果。
3. 代码及测试
package cn.pku.edu.algorithm.leetcode.plus;
import cn.pku.edu.algorithm.leetcode.common.TreeNode;
import java.util.*;
/**
* @author allen
* @date 2022/9/19
*/
public class LevelOrderBottom
public static void main(String[] args)
TreeNode root = new TreeNode(1);
TreeNode treeNode2 = new TreeNode(2);
TreeNode treeNode3 = new TreeNode(3);
TreeNode treeNode4 = new TreeNode(4);
TreeNode treeNode5 = new TreeNode(5);
TreeNode treeNode6 = new TreeNode(6);
root.left = treeNode2;
root.right = treeNode3;
treeNode2.left = treeNode4;
treeNode3.left = treeNode5;
treeNode3.right = treeNode6;
LevelOrderBottom levelOrderBottom = new LevelOrderBottom();
int[][] res = levelOrderBottom.levelOrderBottom(root);
for (int[] level: res)
for (int num: level)
System.out.print(num + " ");
System.out.println();
public int[][] levelOrderBottom(TreeNode root)
List<int[]> out = new ArrayList<>();
int[] level = new int[1];
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int cur = 1, next = 0;
int index = 0; // index of current level
while (!queue.isEmpty())
TreeNode node = queue.poll();
level[index++] = node.val;
cur--;
if (node.left != null)
queue.add(node.left);
next++;
if (node.right != null)
queue.add(node.right);
next++;
if (cur == 0)
out.add(level);
cur = next;
next = 0;
level = new int[cur];
index = 0;
int[][] res = new int[out.size()][];
index = 0; // index of level
for (int i = out.size() - 1; i >= 0; i--)
res[index++] = out.get(i);
return res;
以上是关于算法从下到上打印二叉树的主要内容,如果未能解决你的问题,请参考以下文章