Java实现完全二叉树,实现非递归前序,中序,后序遍历

一、定义二叉树

二叉树可以保存在数组,节点在树中位置与数组中索引相关,
比如最后一个根节点 index= N/2向下取整,i 的左节点 索引是 2i 右节点 2i+1 (从一开始)
public class TreeByList {

	//数组记录节点 适用于完全二叉树 不然很浪费空间
	static String[] s = new String[] { "1", "2", "3", "4", "5", "6", "7", "8" };

	public static class Node {
		Node left;
		Node right;
		String data;

		Node(String data) {
			this.data = data;
			this.left = null;
			this.right = null;
		}
	}

	public static LinkedList<Node> nodeList = new LinkedList<Node>();

	public static void initTree() {
		// 初始化所有数组元素为链表节点
		for (String str : s) {
			nodeList.add(new Node(str));
		}
		int len = s.length;
		int rootIndex;
		//完全二叉树特点 最后根节点在数组索引是 总数/2 向下取整
		for (rootIndex = 0; rootIndex < len / 2 - 1; rootIndex++) {
			int leftIndex = rootIndex * 2 + 1;
			int rightIndex &
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/* * 基于向量实现完全二叉树 */ package dsa; public class ComplBinTree_Vector extends BinTree_LinkedList implements ComplBinTree { private Vector T;//向量 //构造方法:默认的空树 public ComplBinTree_Vector() { T = new Vector_ExtArray(); root = null; } //构造方法:按照给定的节点序列,批量式建立完全二叉树 public ComplBinTree_Vector(Sequence s) { this(); if (null !=s) while (!s.isEmpty()) addLast(s.removeFirst()); } /*---------- BinaryTree接口中各方法的实现 ----------*/ //返回树根(重写) public BinTreePosition getRoot() { return T.isEmpty() ? null : posOfNode(0); } //判断是否树空(重写) public boolean isEmpty() { return T.isEmpty(); } //返回树的规模(重写) public int getSize() { return T.getSize(); } //返回树(根)的高度(重写) public int getHeight() {return isEmpty() ? -1 : getRoot().getHeight(); } /*---------- ComplBinTree接口中各方法的实现 ----------*/ //生成并返回一个存放e的外部节点,该节点成为新的末节点 public BinTreePosition addLast(Object e) { BinTreePosition node = new ComplBinTreeNode_Rank(T, e); root = (BinTreePosition) T.getAtRank(0); return node; } //删除末节点,并返回其中存放的内容 public Object delLast() { if (isEmpty()) return null;//若树(堆)已空,无法删除 if (1 == getSize()) root = null;//若删除最后一个节点,则树空 return T.removeAtRank(T.getSize()-1); } //返回按照层次遍历编号为i的节点的位置,0 <= i < size() public BinTreePosition posOfNode(int i) { return (BinTreePosition)T.getAtRank(i); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值