Java语言实现二叉树及其操作

public class TNode {// 二叉树结点类
	public Object val; // 结点值
	public TNode lChild;// 左结点
	public TNode rChild;// 右结点
}
	
public TNode(Object val) {
	this.val = val;
}

1.数组构建二叉树

	public TNode createBiTree(Object... values) {
		if (values == null || values.length == 0) {
			return null;
		}
		return createBiTree(values, 0);
	}

	private TNode createBiTree(Object[] values, int index) {
		TNode root = null;
		if (index < values.length) {
			if (values[index] == null) {
				return null;
			}
			root = new TNode(values[index]);
			root.lChild = createBiTree(values, 2 * index + 1);
			root.rChild = createBiTree(values, 2 * index + 2);
		}
		return root;
	}

例如:用数组{1,2,3,null,4,null,5}构建的二叉树是这样的:
在这里插入图片描述
2.二叉树的遍历

	public void preOrder(TNode root) {// 非递归先序遍历
		if (root == null) {
			return;
		}
		Stack<TNode> s = new Stack<TNode>();
		while (true) {
			while (root != null) {
				System.out.println(root.val);
				s.push(root);
				root = root.lChild;
			}
			if (s.isEmpty()) {
				break;
			}
			root = s.pop().rChild;
		}
	}

	public void inOrder(TNode root) {// 非递归中序遍历
		if (root == null) {
			return;
		}
		Stack<TNode> s = new Stack<TNode>();
		while (true) {
			while (root != null) {
				s.push(root);
				root = root.lChild;
			}
			if (s.isEmpty()) {
				break;
			}
			root = s.pop();
			System.out.println(root.val);
			root = root.rChild;
		}
	}

	public void postOrder(TNode root) {// 非递归后序遍历
		if (root == null) {
			return;
		}
		Stack<TNode> s = new Stack<TNode>();
		Stack<Integer> s2 = new Stack<Integer>();
		Integer i = new Integer(1);
		while (root != null || !s.isEmpty()) {
			while (root != null) {
				s.push(root);
				s2.push(0);
				root = root.lChild;
			}
			while (!s.empty() && s2.peek().equals(i)) {
				s2.pop();
				System.out.println(s.pop().val);
			}
			if (!s.empty()) {
				s2.pop();
				s2.push(i);
				root = s.peek().rChild;
			}
		}
	}

	public void levOrder(TNode root) {// 层次遍历
		if (root == null) {
			return;
		}
		LinkedList<TNode> q = new LinkedList<TNode>();
		q.addLast(root);
		while (!q.isEmpty()) {
			TNode out = q.removeFirst();
			System.out.println(out.val);
			if (out.lChild != null) {
				q.addLast(out.lChild);
			}
			if (out.rChild != null) {
				q.addLast(out.rChild);
			}
		}
	}

3.求第k层的节点数

public getNodeNumOfK(TNode root,int k) {
	if(root == null || k<=0)  return 0;
	if(k == 1) return 1;
	k--;
	return getNodeNumOfK(root.lChild,k)+getNodeNumOfK(root.rChild,k);
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值