二叉树算法总结

来源:互联网 发布:js判断浏览器是否是ie 编辑:程序博客网 时间:2024/06/11 02:40

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);    }


0 0
原创粉丝点击