树的常用术语:
1.节点
2.根节点
3.父节点
4.子节点
5.叶子节点 (没有子节点的节点)
6.节点的权(节点值)
7.路径(从 root 节点找到该节点的路线)
8.层
9.子树
10.树的高度(最大层数)
11. 森林 :多颗子树构成森林
二叉树遍历说明:
前序遍历: 先输出父节点,再遍历左子树和右子树
中序遍历: 先遍历左子树,再输出父节点,再遍历右子树
后序遍历: 先遍历左子树,再遍历右子树,最后输出父节点
public class BinaryTreeDem { public static void main(String[] args) { BinaryTree binaryTree = new BinaryTree(); TreeNode root=new TreeNode(1,"赵政"); TreeNode node2=new TreeNode(2,"字通"); TreeNode node3=new TreeNode(3,"孟德"); TreeNode node4=new TreeNode(4,"敬真"); TreeNode node5=new TreeNode(5,"国瑞"); root.setLeft(node2); root.setRight(node3); node2.setLeft(node4); node2.setRight(node5); binaryTree.setRoot(root); System.out.println("后序遍历"); binaryTree.postOrder(); System.out.println("中序遍历"); binaryTree.infixOrder(); System.out.println("前序遍历"); binaryTree.preOrder(); } } class BinaryTree{ private TreeNode root; public void setRoot(TreeNode root) { this.root = root; } //前序 public void preOrder() { if(this.root!=null){ this.root.preOrder(); }else { System.out.println("二叉树为空无法遍历"); } } //中序 public void infixOrder() { if(this.root!=null) { this.root.infixOrder(); }else { System.out.println("二叉树为空无法遍历"); } } //后序 public void postOrder() { if(this.root!=null) { this.root.postOrder(); }else { System.out.println("二叉树为空无法遍历"); } } } class TreeNode{ private int no; private String name; private TreeNode left; private TreeNode right; public TreeNode(int no, String name) { this.no = no; this.name = name; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getName() { return name; } public void setName(String name) { this.name = name; } public TreeNode getLeft() { return left; } public void setLeft(TreeNode left) { this.left = left; } public TreeNode getRight() { return right; } public void setRight(TreeNode right) { this.right = right; } @Override public String toString() { return "TreeNode [no=" + no + ", name=" + name + "]"; } //前序 public void preOrder() { System.out.println(this);//先输入父节点 //递归向左子树前序遍历 if(this.left!=null) { this.left.preOrder(); } //递归向右子树前序遍历 if(this.right!=null) { this.right.preOrder(); } } //中序 public void infixOrder() { if(this.left!=null) { this.left.infixOrder(); } System.out.println(this); if(this.right!=null) { this.right.infixOrder(); } } //后序 public void postOrder() { if(this.left!=null) { this.left.postOrder(); } if(this.right!=null) { this.right.postOrder(); } System.out.println(this); } }