二叉樹的是常見的數據結構,二叉樹的遍歷有三種,分別爲前序遍歷、中序遍歷和後序遍歷。下面看看使用Java實現二叉樹。java
如下圖爲例sql
前序遍歷:ABDEGCFbash
中序遍歷:DBGEACF數據結構
後序遍歷:DGEBFCAide
JAVA實現須要創建三個類post
下面是Java代碼ui
TreeNode.javathis
package Tree;
public class TreeNode {
private final char value;
private TreeNode left;
private TreeNode right;
public TreeNode(char value) {
this.value=value;
this.left=null;
this.right=null;
}
public char getValue() {
return value;
}
public TreeNode getLeft() {
return left;
}
public void setLefg(TreeNode left) {
this.left=left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right=right;
}
}
複製代碼
2.TreeCreator.javaspa
package Tree;
public class TreeCreator {
public TreeNode creatorSampleTree() {
TreeNode root =new TreeNode('A');
root.setLefg(new TreeNode('B'));
root.getLeft().setLefg(new TreeNode('D'));
root.getLeft().setRight(new TreeNode('E'));
root.getLeft().getRight().setLefg(new TreeNode('G'));
root.setRight(new TreeNode('C'));
root.getRight().setRight(new TreeNode('F'));
return root;
}
}
複製代碼
3.TreeTreavervsal.javacode
package Tree;
import javax.sql.rowset.spi.SyncProvider;
public class TreeTraversal {
public void preOrder(TreeNode root) {
if(root == null) {
return;
}
System.out.print(root.getValue());
preOrder(root.getLeft());
preOrder(root.getRight());
}
public void inOrder(TreeNode root) {
if(root == null) {
return;
}
inOrder(root.getLeft());
System.out.print(root.getValue());
inOrder(root.getRight());
}
public void postOrder(TreeNode root) {
if(root == null) {
return;
}
postOrder(root.getLeft());
postOrder(root.getRight());
System.out.print(root.getValue());
}
public static void main(String[] args) {
TreeCreator creator=new TreeCreator();
TreeTraversal treaversal =new TreeTraversal();
TreeNode sampleTree=creator.creatorSampleTree();
treaversal.preOrder(sampleTree);
System.out.println();
treaversal.inOrder(sampleTree);
System.out.println();
treaversal.postOrder(sampleTree);
}
}
複製代碼
例如:
前序遍歷:ABDEGCF
中序遍歷:DBGEACF
基本思想:根據前序遍歷的特色得出A爲根節點,那麼中心遍歷的A也爲根節點,那麼根據中序遍歷特色A左邊的爲A的左子樹,即DBGE爲左子樹,CF爲右子樹數,以此遞歸,求出樹,而後最終得出後續遍歷。
Java代碼
public TreeNode creatorTree(String preOrder,String inOrder) {
if(preOrder.equals("")) {
return null;
}
char rootValue=preOrder.charAt(0);
int rootIndex =inOrder.indexOf(rootValue);
TreeNode root=new TreeNode(rootValue);
root.setLefg(
creatorTree(
preOrder.substring(1, rootIndex+1),
inOrder.substring(0, rootIndex)));
root.setRight(creatorTree(
preOrder.substring(1+rootIndex),
inOrder.substring(1+rootIndex)
));
return root;
}
複製代碼