树---关于二叉树的三个小算法

package com.Tree;
/*
 *  这个类包含三个有关二叉树操作的小算法
 *  1.计算某一结点所在层次
 *  2.交换二叉树所有结点的左右子树位置
 *  3.删除二叉树以某一结点为根节点的子树
 */
import java.util.*;

public class ThreeAlgrithms {
	//1.计算某一结点所在层次
	public int layerNode(BTNode p, int key) {
		Stack<BTNode> stack1 = new Stack<BTNode>();
		Stack<Integer> stack2 = new Stack<Integer>();
		int posi = 1;
		
		while (p != null || stack1.empty() == false) {
			while (p != null) {
				if (p.data == key)
					return posi;
				stack1.push(p);
				stack2.push(posi);
				p = p.left;
				posi++;
			}
			p = stack1.pop();
			posi = stack2.pop();
			p = p.right;
			posi++;
		}
		return posi-1;
	}
	
	//2.交换二叉树所有结点的左右子树位置
	public void exchangeBT(BTNode p) {
		Queue<BTNode> queue = new LinkedList<BTNode>();
		
		while (p != null) {
			BTNode temp = p.left;
			p.left = p.right;
			p.right = temp;
			
			if (p.left != null)
				queue.offer(p.left);
			if (p.right != null)
				queue.offer(p.right);
			p = queue.poll();
		}
	}
	
	//3.删除二叉树以某一结点为根节点的子树
	public void delSubTree(BTNode p, int key) {
		Stack<BTNode> stack = new Stack<BTNode>();
		BTNode q = p;
		
		if (p.data == key) {
			//怎么释放p对象 
			p = null;
			return;
		}
		while (p != null || stack.empty() == false) {											
			while (p != null) {
				if (p.data == key) {
					if (q.left == p)
						q.left = null;
					else
						q.right = null;
					//怎么释放p对象 
					p = null;
					return;
				}
				stack.push(p);
				q = p;
				p = p.left;
			}
			p = stack.pop();
			p = p.right;
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值