Java實現二叉樹
1. 定義結點類
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
2. 構建二叉樹

public static TreeNode createBT(int[] arr, int i) // 初始時,傳入的i==0
{
TreeNode root = null; // 定義根節點
if (i >= arr.length) // i >= arr.length 時,表示已經到達了根節點
return null;
root = new TreeNode(arr[i]); // 根節點
root.left = createBT(arr, 2*i+1); // 遞歸建立左孩子結點
root.right = createBT(arr, 2*i+2); // 遞歸建立右孩子結點
return root;
}
3. 遍歷二叉樹
3.1 先序遍歷
// 先序遍歷
public static void PreOrder(TreeNode root)
{
if (root == null)
return;
System.out.print(root.val+" ");
PreOrder(root.left);
PreOrder(root.right);
}
3.2 中序遍歷
// 中序遍歷
public static void InOrder(TreeNode root)
{
if (root == null)
return;
InOrder(root.left);
System.out.print(root.val+" ");
InOrder(root.right);
}
3.3 后序遍歷
// 后序遍歷
public static void PostOrder(TreeNode root)
{
if (root == null)
return;
PostOrder(root.left);
PostOrder(root.right);
System.out.print(root.val+" ");
}
4. 總代碼
package com.BinaryTree;
// 定義(鏈式存儲)二叉樹結點
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6};
TreeNode root = createBT(arr, 0);
System.out.println("先序遍歷:");
PreOrder(root);
System.out.println("\n中序遍歷:");
InOrder(root);
System.out.println("\n后序遍歷:");
PostOrder(root);
}
// 使用一維數組建樹(利用性質:在一維數組中, 第i個結點的左孩子結點是第2*i+1個結點, 第i個結點的右孩子結點是第2*i+2個結點)
public static TreeNode createBT(int[] arr, int i)
{
TreeNode root = null; // 定義根節點
if (i >= arr.length) // i >= arr.length 時,表示已經到達了根節點
return null;
root = new TreeNode(arr[i]); // 根節點
root.left = createBT(arr, 2*i+1); // 遞歸建立左孩子結點
root.right = createBT(arr, 2*i+2); // 遞歸建立右孩子結點
return root;
}
// 先序遍歷
public static void PreOrder(TreeNode root)
{
if (root == null)
return;
System.out.print(root.val+" ");
PreOrder(root.left);
PreOrder(root.right);
}
// 中序遍歷
public static void InOrder(TreeNode root)
{
if (root == null)
return;
InOrder(root.left);
System.out.print(root.val+" ");
InOrder(root.right);
}
// 后序遍歷
public static void PostOrder(TreeNode root)
{
if (root == null)
return;
PostOrder(root.left);
PostOrder(root.right);
System.out.print(root.val+" ");
}
}
/* 運行結果:
先序遍歷:
1 2 4 5 3 6
中序遍歷:
4 2 5 1 6 3
后序遍歷:
4 5 2 6 3 1
*/