二叉树算法总结

1,求二叉树的深度

package com.dong.istudy.btree;

/**
 * 获取二叉树的深度
 */
public class BTreeDeep {

	public static void main(String[] args) {

	}

	public static int getDeep(BTreeNode root) {
		if (root == null) {
			return 0;
		}
		int nleft = getDeep(root.left);
		int nright = getDeep(root.right);

		return (nleft > nright) ? (nleft + 1) : (nright + 1);		//最初学的时候一直不懂,其实这是记录的递归层数
	}
}

2,判断一个数组是不是一个二元查找树的后续遍历的结果

package com.dong.istudy.btree;

/**
 * 判断一个数组是不是一个二元查找树的后续遍历的结果
 * 
 * 如果一个数组是一个二元查找树的后续遍历,那么遍历的最后一个节点肯定是树的根
 * 递归的算法,即先通过遍历数组的方法把左子树取出来,那么剩下的元素肯定都是右子树
 * 的元素,因此判断右子树是不是都比跟节点大
 *
 */
public class BSTreeJudger {

	public static void main(String[] args) {

	}

	public boolean JudgeTree(int[] array) {
		if (array.length == 0 || array == null)
			return true;

		int root = array[array.length - 1];
		int index = 0;
		// 先把数组的左子树取出来
		while (array[index] < root) {
			index++;
		}
		// 然后判断余下的是不是符合他的右子树()
		for (int i = index; i < array.length - 1; i++) {
			if (array[i] <= root)
				return false;
		}

		// 分别构造左子树和右子树
		int[] leftArray = new int[index];
		int[] rightArray = new int[array.length - index - 1];

		for (int i = 0; i < index; i++) {
			leftArray[i] = array[i];
		}
		for (int i = index; i < array.length - 1; i++) {
			rightArray[i - index] = array[i];
		}

		return JudgeTree(leftArray) && JudgeTree(rightArray);
	}

}

3,求二元查找树的镜像

package com.dong.istudy.btree;

public class MirrorBTree {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

	}
	
	public void MirrorRecursively(BTreeNode root) {
		
		if(null == root) {
			return ;
		}
		BTreeNode temp = root.left;
		root.left = root.right;
		root.right = temp;
		
		if(root.left != null) {
			MirrorRecursively(root.left);
		}
		if(root.right != null) {
			MirrorRecursively(root.right);
		}
		
	}

}

4,把二元查找树转换为双向链表

 /**
     * 利用中序遍历,把二元查找树转换为有序的双向链表
     * @param root
     */
    static void midOrder(BTree root){
        if(root == null) 
        	return ;
        midOrder(root.left);
        convertToDoubleList(root);
//        System.out.print("-"+root.data);
        midOrder(root.right);
    }
   

static BTree pHead = null;			//指向循环队列头结点
    static BTree pIndex=null;			//指最后一个结点
     
    static void convertToDoubleList(BTree pCurrent) {
        pCurrent.left = pIndex;			//使当前结点的左指针指向双向链表中最后一个结点
        if (null == pIndex) {			//若最后一个元素不存在,此时双向链表尚未建立,因此将当前结点设为双向链表头结点
           pHead = pCurrent;
        } else {						//使双向链表中最后一个结点的右指针指向当前结点
           pIndex.right = pCurrent;
        }
     
        pIndex = pCurrent;//将当前结点设为双向链表中最后一个结点
        System.out.print("  " + pCurrent.data);
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值