顺序存储二叉树的遍历

顺序存储二叉树一个结点下标为n,则其左结点的下标为2*n+1,右结点下标为2*n+2,一个结点的父结点下标为(n-1)/2,因此可以利用递归很容易的写出其遍历方式,这里给出前序遍历示例:

//顺序存储二叉树前遍历
public class ArrBinaryTreeDemo {
	public static void main(String[] args) {
		int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
		ArrBinaryTree arrBinaryTree = new ArrBinaryTree(arr);
		arrBinaryTree.preOrder();
	}
}

class ArrBinaryTree {
	private int[] arr;

	public ArrBinaryTree(int[] arr) {
		this.arr = arr;
	}

	// index表示数组的下标
	public void preOrder(int index) {
		// 如果数组为空,或者arr.length=0
		if (arr == null || arr.length == 0) {
			System.out.println("数组为空,不能按照二叉树的前序遍历");
		}
		System.out.println(arr[index]);
		// 向左递归遍历
		if ((index * 2 + 1) < arr.length) {
			preOrder(2 * index + 1);
		}
		// 向右递归遍历
		if ((index * 2 + 2) < arr.length) {
			preOrder(2 * index + 2);
		}
	}

	// 重载preOrder
	public void preOrder() {
		preOrder(0);
	}
}
imn
发布了33 篇原创文章 · 获赞 0 · 访问量 365

猜你喜欢

转载自blog.csdn.net/qq_45955462/article/details/104703162