二叉树遍历 前序 中序 后序
package com.pay.test; import java.util.LinkedList; public class Node { private Integer data; private Node left; private Node right; public Integer getData() { return data; } public void setData(Integer data) { this.data = data; } public Node getLeft() { return left; } public void setLeft(Node left) { this.left = left; } public Node getRight() { return right; } public void setRight(Node right) { this.right = right; } public Node(Integer data) { this.data = data; } public static Node createNode(LinkedList<Integer> list){ if(list==null || list.isEmpty()){ return null; } Integer data= list.removeFirst(); Node node; if(data!=null ){ node=new Node(data);
return node; } return null; } //前序遍历 public void preOrderPrint(Node root){ if(root==null){ return; }else { System.out.println(root.data+""); preOrderPrint(root.left); preOrderPrint(root.right); } } //中序遍历 public void inOrderPrint(Node node){ if(node==null){ return; }else { inOrderPrint(node.left); System.out.println(node.data); inOrderPrint(node.right); } } //后续遍历 public void postOrderPrint(Node node){ if(node==null){ return; }else { postOrderPrint(node.left); postOrderPrint(node.right); System.out.println(node.data); } } }
测试类
package com.pay.test; public class Test { public static void main(String[] args) { Node root=new Node(1); Node left=new Node(22); Node left1=new Node(44); Node left2=new Node(44); Node right=new Node(55); Node right1=new Node(6); Node right2=new Node(7); left1.setLeft(left2); left.setLeft(left1); root.setLeft(left); right1.setRight(right2); right.setRight(right1); root.setRight(right); System.out.println("前序遍历"); root.preOrderPrint(root); System.out.println("中序遍历"); root.inOrderPrint(root); System.out.println("后序遍历"); root.postOrderPrint(root); } }