考察点
树的遍历
知识点
题目
分析
题目要求从上到下打印二叉树,类似这种题目的思路就是用归纳法,通过一些例子找到数据的规律找一个合适的数据结构,这道题目很明显不能按照树的三种遍历方式去解,要按照6,10,5,7,9,11的顺序遍历,5和7是6的子结点,9和11是10的子结点,也就是说需要先遍历完父结点,再遍历子结点,同时在遍历父结点的时候要先把子结点存到这个数据结构里面,同时要求先入先出,那么很明显这个结构就是队列
import java.util.Queue;
import java.util.LinkedList;
public class BinaryTree {
Node root;
public BinaryTree() {
this.root = null;
}
public void insertTree(int val) {
if (this.root == null) {
Node root = new Node(val);
this.root = root;
} else {
insertChildTree(this.root,val);
}
}
public void insertChildTree(Node node,int val) {
if (node != null && val < node.val) {
if (node.leftChild == null) {
node.leftChild = new Node(val);
} else {
insertChildTree(node.leftChild,val);
}
}
if (node != null && val > node.val) {
if (node.rightChild == null) {
node.rightChild = new Node(val);
} else {
insertChildTree(node.rightChild,val);
}
}
}
public Node getRoot() {
return this.root;
}
public void levelPrint(Node root) {
Queue q = new LinkedList<>();
q.add(root);
while(q.size() > 0) {
Node node = (Node) q.remove();
System.out.println(node.val);
if (node.leftChild != null) {
q.add(node.leftChild);
}
if (node.rightChild != null) {
q.add(node.rightChild);
}
}
}
}
public class Node{
int val;
Node leftChild;
Node rightChild;
public Node(int data) {
this.val = data;
this.leftChild = null;
this.rightChild = null;
}
}
public class TwentyThree {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.insertTree(8);
tree.insertTree(6);
tree.insertTree(10);
tree.insertTree(5);
tree.insertTree(7);
tree.insertTree(9);
tree.insertTree(11);
tree.levelPrint(tree.getRoot());
}
}