建树1
Posted cherry-bail
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了建树1相关的知识,希望对你有一定的参考价值。
构建一颗二叉树,以列表形式打印
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val){
this.val = val;
}
}
import java.util.ArrayList;
import java.util.Stack;
/**
* @author bailu
* @version: 2020年7月6日 下午10:38:32
*
* @file: PrintTreeFromTopBottom.java
* @declaration:
*/
public class PrintTreeFromTopBottom {
/**
* @function
*
* @parameters
*
* @return void
*/
public static void main(String[] args) {
TreeNode a = new TreeNode(2);
a.left = new TreeNode(4);
a.right = new TreeNode(6);
a.left.left = new TreeNode(7);
a.left.right = new TreeNode(9);
a.right.right = new TreeNode(21);
a.right.left = new TreeNode(14);
ArrayList<Integer> list = printTreeFromTopBottom(a); //列表打印
System.out.println(list);
ArrayList<ArrayList<Integer>> list2 = printTreewithGraph(a); //按行打印
System.out.println(list2);
}
public static ArrayList<Integer> printTreeFromTopBottom(TreeNode root){
ArrayList<Integer> list = new ArrayList<>();
ArrayList<TreeNode> queue = new ArrayList<>();
if(root == null) {
return list;
}
queue.add(root);
while(queue.size() != 0) {
TreeNode temp = queue.remove(0);
if(temp.left != null) {
queue.add(temp.left);
}
if(temp.right != null) {
queue.add(temp.right);
}
list.add(temp.val);
}
return list;
}
public static ArrayList<ArrayList<Integer>> printTreewithGraph(TreeNode root){
//result用来存储结果
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
//创建两个辅助栈,分别存放奇数行和偶数行的节点
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
//创建集合,存放每一行的节点值
ArrayList<Integer> list = new ArrayList<>();
boolean flag = true; //true为奇数行
TreeNode node;
stack1.push(root);
while (!stack1.isEmpty() || !stack2.isEmpty()) {
//奇数行,从左往右入栈stack2
if (flag) {
while (!stack1.isEmpty()) {
node = stack1.pop();
list.add(node.val);
if (node.right != null) {
stack2.push(node.right);
}
if (node.left != null) {
stack2.push(node.left);
}
if (stack1.isEmpty()) {
result.add(list);
list = new ArrayList<>();
}
}
} else {
//偶数行,将入栈的奇数行出栈到stack1
while (!stack2.isEmpty()) {
node = stack2.pop();//由于后进先出,所以弹出的是右子树
list.add(node.val);//将右节点存入
if (node.right != null) {
stack1.push(node.right);
}
if (node.left != null) {
stack1.push(node.left);
}
if (stack2.isEmpty()) {
result.add(list);
list = new ArrayList<>();
}
}
}
flag = !flag;
}
return result;
}
}
以上是关于建树1的主要内容,如果未能解决你的问题,请参考以下文章