二叉树的创建
目录
一、二叉树的定义
二、代码定义
三、遍历二叉树
1、前序遍历
2、中序遍历
3、后序遍历
四、方法的使用
一、二叉树的定义
二叉树(binary tree)是指树中节点的度不大于2的有序树,它是一种最简单且最重要的树。二叉树的递归定义为:二叉树是一棵空树,或者是一棵由一个根节点和两棵互不相交的,分别称作根的左子树和右子树组成的非空树;左子树和右子树又同样都是二叉树 。
二、代码定义
二叉树通过左值和右值连接起来
public class BinaryTree {static class TreeNode{public char val;public TreeNode left;public TreeNode right;public TreeNode(char val) {this.val = val;}}public TreeNode creatTree(){TreeNode A=new TreeNode('A');TreeNode B=new TreeNode('B');TreeNode C=new TreeNode('C');TreeNode D=new TreeNode('D');TreeNode E=new TreeNode('E');TreeNode F=new TreeNode('F');TreeNode G=new TreeNode('G');TreeNode H=new TreeNode('H');A.left=B;A.right=C;B.left=D;B.right=E;C.left=F;C.right=G;E.right=H;return A;}
三、遍历二叉树
1、前序遍历
前序遍历的顺序为:根结点--->根的左子树--->根的右子树
void preorder(TreeNode root){if (root==null){return;}System.out.print(root.val+" ");preorder(root.left);preorder(root.right);}
2、中序遍历
中序遍历的顺序为:根的左子树--->根结点--->根的右子树
void inorder(TreeNode root){if ((root==null)){return;}inorder(root.left);System.out.print(root.val+" ");inorder(root.right);}
3、后序遍历
后序遍历的顺序为:根的左子树--->根的右子树--->根结点
void postorder(TreeNode root){if (root==null){return;}postorder(root.left);postorder(root.right);System.out.print(root.val+" ");}}
四、方法的使用
public class Main {public static void main(String[] args) {BinaryTree binaryTree=new BinaryTree();BinaryTree.TreeNode root=binaryTree.creatTree();binaryTree.preorder(root);System.out.println();binaryTree.inorder(root);System.out.println();binaryTree.postorder(root);}}
执行结果:
A B D E H C F G
D B E H A F C G
D H E B F G C A