二叉树(Binary Tree)是树的一种常见形式。二叉树的任意结点最多可以有两个子结点,也可以只有一个或者没有子结点。因此二叉树的度数一定小于等于2。二叉树结点的两个子结点,一个被称为左子结点,一个被称为右子结点。二叉树严格区分左右子结点,两个子结点的顺序是固定的,即使只有一棵子树也要区分左右。
public class BinaryTree {TreeNode root;public BinaryTree() {this.root = null;}public void insert(int val) {root = insertRecursive(root, val);}private TreeNode insertRecursive(TreeNode root, int val) {if (root == null) {return new TreeNode(val);}if (val < root.val) {root.left = insertRecursive(root.left, val);} else if (val > root.val) {root.right = insertRecursive(root.right, val);}return root;}public void preOrderTraversal(TreeNode node) {if (node != null) {System.out.print(node.val + " ");preOrderTraversal(node.left);preOrderTraversal(node.right);}}public static void main(String[] args) {BinaryTree tree = new BinaryTree();tree.insert(5);tree.insert(3);tree.insert(7);tree.insert(2);tree.insert(4);System.out.println("Preorder traversal of binary tree is:");tree.preOrderTraversal(tree.root);}class TreeNode {int val;TreeNode left;TreeNode right;public TreeNode(int val) {this.val = val;this.left = null;this.right = null;}}
}
一个二叉树类 BinaryTree
和一个节点类 TreeNode
,实现了二叉树的插入操作和先序遍历算法。