二叉树的基本概念:二叉树是递归定义的,其节点有左右子树之分,逻辑上二叉树有五种形态:1)空二叉树 2)只有一个根节点的二叉树 3)只有左子树 4)只有右子树 5)完全二叉树
二叉树的创建
private static class Node{
private char val;
private Node left;
private Node right;
private Node(char val) {
this.val=val;
}
}
public static Node buildTree(){
Node a=new Node('A');
Node b=new Node('B');
Node c=new Node('C');
Node d=new Node('D');
Node e=new Node('E');
Node f=new Node('F');
Node g=new Node('G');
Node h=new Node('H');
a.left=b; a.right=c;
b.left=d;b.right=e;
c.left=f;c.right=g;
e.right=h;
return a;
}
二叉树的前,中,后序遍历
前序遍历:若二叉树为空,则返回null;否则
1)访问根节点
2)先序遍历左子树
2)先序遍历右子树
中序遍历:若二叉树为空,则返回null;否则
1)中序遍历左子树
2)访问根节点
3)中序遍历右子树
后序遍历:若二叉树为空,则返回null;否则
1)后序遍历左子树
2)后续遍历右子树
3)访问根节点
public static void preOrderTraversal(Node root) {
//线序遍历
//根+左子树的前序遍历+右子树的先序遍历
if(root==null) {
return ;
}
System.out.println(root);
preOrderTraversal(root.left);
preOrderTraversal(root.right);
}
public static void inOrderTraversal(Node root) {
//中序遍历
//左子树的中序遍历+根+右子树的中序遍历
if(root==null) {
return ;
}
inOrderTraversal(root.left);
System.out.println(root);
inOrderTraversal(root.right);
}
public static void postOrderTraversal(Node root) {
//后续遍历二叉树
if(root==null) {
return;
}
postOrderTraversal(root.left);
postOrderTraversal(root.right);
System.out.println(root);
}
完整代码:
public class BineryTree {
private static class Node{
private char val;
private Node left;
private Node right;
private Node(char val) {
this.val=val;
}
}
public static Node buildTree(){
Node a=new Node('A');
Node b=new Node('B');
Node c=new Node('C');
Node d=new Node('D');
Node e=new Node('E');
Node f=new Node('F');
Node g=new Node('G');
Node h=new Node('H');
a.left=b; a.right=c;
b.left=d;b.right=e;
c.left=f;c.right=g;
e.right=h;
return a;
}
public static void preOrderTraversal(Node root) {
//线序遍历
//根+左子树的前序遍历+右子树的先序遍历
if(root==null) {
return ;
}
System.out.println(root);
preOrderTraversal(root.left);
preOrderTraversal(root.right);
}
public static void inOrderTraversal(Node root) {
//中序遍历
//左子树的中序遍历+根+右子树的中序遍历
if(root==null) {
return ;
}
inOrderTraversal(root.left);
System.out.println(root);
inOrderTraversal(root.right);
}
public static void postOrderTraversal(Node root) {
//后续遍历二叉树
if(root==null) {
return;
}
postOrderTraversal(root.left);
postOrderTraversal(root.right);
System.out.println(root);
public static void main(String[] args) {
Node root=buildTree();
System.out.println("Succcess");
preOrderTraversal(root);
System.out.println("====================");
inOrderTraversal(root);
System.out.println("=====================");
postOrderTraversal(root);
System.out.println("=====================");
}