树的结构如下:
static class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
public TreeNode() {
}
}
public static void main(String[] args) {
TreeNode node8=new TreeNode(8,null,null);
TreeNode node7=new TreeNode(7,null,null);
TreeNode node6=new TreeNode(6,node7,null);
TreeNode node5=new TreeNode(5,null,null);
TreeNode node4=new TreeNode(4,null,node8);
TreeNode node3=new TreeNode(3,node6,null);
TreeNode node2=new TreeNode(2,node4,node5);
TreeNode node1=new TreeNode(1,node2,node3);
//前序
preOrder1(node1);
preOrder2(node1);
System.out.println("**************中序**************");
//中序
midOrder1(node1);
midOrder2(node1);
System.out.println("**************后序**************");
//后序遍历
// postOrder1(node1);
postOrder2(node1);
System.out.println("**************层序遍历**************");
levelOrder(node1);
}
//层次遍历
private static void levelOrder(TreeNode root) {
Queue<TreeNode>queue=new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()){
TreeNode node =queue.poll();
if (node != null) {
System.out.print(node.val);
queue.add(node.left);
queue.add(node.right);
}
}
}
//后序遍历迭代
private static void postOrder2(TreeNode root) {
if (root==null){
return;
}
Deque<TreeNode> stack=new LinkedList<>();
TreeNode pre=null;
stack.push(root);
while (!stack.isEmpty()||root!=null){
while (root!=null){
stack.push(root);
root=root.left;
}
root=stack.pop();
if (root.right==null||root.right==pre){
System.out.println(root.val);
pre=root;
root=null;
}else {
stack.push(root);
root=root.right;
}
}
}
//后序递归
private static void postOrder1(TreeNode root) {
if (root==null)return;
postOrder1(root.left);
postOrder1(root.right);
System.out.println(root.val);
}
//中序迭代
private static void midOrder2(TreeNode root) {
if (root!=null){
Stack<TreeNode> stack=new Stack<>();
while (!stack.isEmpty()||root!=null){
if (root!=null){
stack.add(root);
root=root.left;
}else {
root=stack.pop();
System.out.println(root.val);
root=root.right;
}
}
}
}
//中序递归
private static void midOrder1(TreeNode root) {
if (root==null)return;
midOrder1(root.left);
System.out.println(root.val);
midOrder1(root.right);
}
//前序递归
private static void preOrder1(TreeNode root) {
if (root==null)return;
System.out.println(root.val);
// preOrder1(root.left);
preOrder2(root.right);
}
//前序迭代
private static void preOrder2(TreeNode root) {
if (root!=null){
Stack<TreeNode>stack=new Stack<TreeNode>();
stack.add(root);
while (!stack.isEmpty()){
root=stack.pop();
if (root!=null){
System.out.println(root.val);
stack.add(root.right);
stack.add(root.left);
}
}
}
}