一、定义节点结构
package binaryTree;
public class Node {
public int data;
public Node leftNode;
public Node rightNode;
public Node(int key) {
data = key;
}
@Override
public String toString() {
return "Node{" +
"data=" + data +
", leftNode=" + leftNode +
", rightNode=" + rightNode +
'}';
}
}
二、中序遍历
中序遍历的思路是:(左根右)
遇到一个节点,先缓存,看其是否有左子节点,若有,则输出左节点,再输出原节点,最后输出右节点。
该二叉树的中序遍历顺序为:
D -> B -> E ->A -> F -> C -> G
递归
//中序遍历,递归
public void midOrder(Node root){
if(root==null){
return;
}
midOrder(root.leftNode);//左子
System.out.println(root.data);
midOrder(root.rightNode);//右子
}
非递归
//中序遍历,非递归
public void midOrderSimpl(Node root){
Stack<Node>stack=new Stack<>();
Node cur= root;
while(!stack.empty()||cur!=null){
while (cur!=null){
stack.push(cur);
cur=cur.leftNode;
}
cur=stack.pop();
System.out.println(cur.data);
cur=cur.rightNode;
}
}
三、层次遍历
按照二叉树的层次从上至下从左至右进行遍历
该二叉树的层次遍历顺序为:
A -> B -> C -> D -> E -> F ->G
实现思路:
根结点入队;
根结点出队,若其存在左子结点,左子结点入队;若其存在右子结点,右子结点出队;
重复1,2直至队列为空。
public void levelOrder(Node root){
Queue<Node>queue=new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()){
Node cur=queue.poll();
System.out.println(cur.data);
if(cur.leftNode!=null){
queue.add(cur.leftNode);
}if(cur.rightNode!=null){
queue.add(cur.rightNode);
}
}
}
四、测试
package binaryTree;
public class Test828 {
public static void main(String[] args) {
Node node=new Node(1);
Node node1=new Node(2);
Node node2=new Node(3);
Node node3=new Node(4);
Node node4=new Node(5);
node.leftNode=node1;
node.rightNode=node2;
node1.leftNode=node3;
node1.rightNode=node4;
BinaryTree binaryTree=new BinaryTree();
binaryTree.midOrderSimpl(node);
System.out.println("-----------");
binaryTree.levelOrder(node);
}
}
本文含有隐藏内容,请 开通VIP 后查看