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

时间:2023-02-13 22:34:28
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;
		}
	}
}