搜索二叉树创建、遍历、查找

package com.ypzou.about_tree.bstree;


/**
 * 二叉查找树结点,通常使用链式存储方便操作
 */
public class TreeNode {
    
    // key值
    private int      key;
    
    // 用来记录此位置重复节点的个数
    private int      dataNum;
    
    // 下面三个大家都懂得!
    private TreeNode parent;
    
    private TreeNode left;
    
    private TreeNode right;
    
    public TreeNode(int key) {
    
        this.key = key;
        this.dataNum = 1;
    }
    
    public String toString() {
    
        return "key: " + key + " dataNum: " + dataNum;
    }
    
    public void incNumByOne() {
    
        this.dataNum++;
    }
    
    public int getKey() {
    
        return key;
    }
    
    public void setKey(int key) {
    
        this.key = key;
    }
    
    public int getDataNum() {
    
        return dataNum;
    }
    
    public void setDataNum(int dataNum) {
    
        this.dataNum = dataNum;
    }
    
    public TreeNode getParent() {
    
        return parent;
    }
    
    public void setParent(TreeNode parent) {
    
        this.parent = parent;
    }
    
    public TreeNode getLeft() {
    
        return left;
    }
    
    public void setLeft(TreeNode left) {
    
        this.left = left;
    }
    
    public TreeNode getRight() {
    
        return right;
    }
    
    public void setRight(TreeNode right) {
    
        this.right = right;
    }
    

}




package com.ypzou.about_tree.bstree;


import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.Stack;


/**
 * <p>
 * 二叉查找树 二叉查找树性质: 左子树上的结点不比父结点大,右子树上的结点不比父结点小
 * </p>
 * 
 * @ClassName: BSTree
 * @version v 0.1 2018年3月22日 上午11:05:16
 */
public class BSTree {
    
    // 用于随机插入数组中的元素
    private Random   rand     = null;
    
    // 定义根节点
    private TreeNode rootNode = null;
    
    public BSTree(int[] arr) {
    
        rand = new Random();
        createBSTree(arr);
    }
    
    private void createBSTree(int[] arr) {
    
        // 先构建一个存储数组下标的List
        List<Integer> inderootNode = new LinkedList<Integer>();
        int i = 0;
        for (i = 0; i < arr.length; i++) {
            inderootNode.add(i);
        }
        // 随机构造二叉树
        for (i = 0; i < arr.length; i++) {
            int j = 0;
            if (inderootNode.size() > 1) {
                // 随机产生一个数组下标值
                j = rand.nextInt(inderootNode.size() - 1);
            }
            // 插入二叉树
            // TreeInsert(arr[i]);
            TreeInsert(arr[inderootNode.get(j)]);
            // 移除下标
            inderootNode.remove(j);
        }
    }
    
    /**
     * 插入一个整数
     * 
     * @param z
     */
    public void TreeInsert(int z) {
    
        TreeNode parentNode = null;
        TreeNode searchNode = rootNode;
        TreeNode insertNode = new TreeNode(z);
        // while循环找到要插入的点的父结点
        while (searchNode != null) {
            parentNode = searchNode;
            if (insertNode.getKey() < searchNode.getKey()) {
                searchNode = searchNode.getLeft();
            }
            else if (insertNode.getKey() == searchNode.getKey()) {
                // 如果是key值相同的话,直接插入,偷懒在这里...
                searchNode.incNumByOne();
                return;
            }
            else {
                searchNode = searchNode.getRight();
            }
        }
        
        insertNode.setParent(parentNode);
        // 当根节点为空,新插入的节点就是根节点
        if (parentNode == null) {
            rootNode = insertNode;
        }
        else if (insertNode.getKey() < parentNode.getKey()) {
            // 插入左结点
            parentNode.setLeft(insertNode);
        }
        else if (insertNode.getKey() == parentNode.getKey()) {
            // 因为上面插入了,所以这里就不会执行了。
            parentNode.incNumByOne();
            System.out.println("this is not supposed to be erootNodeecuted.");
        }
        else {
            // 插入右结点
            parentNode.setRight(insertNode);
        }
    }
    
    /**
     * 前序遍历二叉搜索树(递归)
     * 
     * @param rootNode
     */
    public void preOrderTreeWalk(TreeNode rootNode) {
    
        if (rootNode != null) {
            System.out.println(rootNode);
            preOrderTreeWalk(rootNode.getLeft());
            preOrderTreeWalk(rootNode.getRight());
        }
    }
    
    /**
     * 中序遍历(递归)
     * 
     * @param rootNode
     */
    public void inOrderTreeWalk(TreeNode rootNode) {
    
        if (rootNode != null) {
            inOrderTreeWalk(rootNode.getLeft());
            System.out.println(rootNode);
            inOrderTreeWalk(rootNode.getRight());
        }
    }
    
    /**
     * 后续遍历(递归)
     * 
     * @param rootNode
     */
    public void postOrderTreeWalk(TreeNode rootNode) {
    
        if (rootNode != null) {
            postOrderTreeWalk(rootNode.getLeft());
            postOrderTreeWalk(rootNode.getRight());
            System.out.println(rootNode);
        }
    }
    
    /**
     * 前序遍历二叉搜索树(非递归)
     * 
     * @param rootNode
     */
    public void preOrderTreeWalkNonrecursive1(TreeNode rootNode) {
    
        Stack<TreeNode> stack = new Stack<TreeNode>();
        while (rootNode != null || !stack.empty()) {
            if (rootNode != null) {
                System.out.println(rootNode);// 遍历输出
                stack.push(rootNode);// 压栈
                rootNode = rootNode.getLeft();
            }
            else {
                rootNode = stack.pop();// 出栈
                rootNode = rootNode.getRight();
            }
        }
    }
    
    public void preOrderTreeWalkNonrecursive2(TreeNode rootNode) {
    
        Stack<TreeNode> stack = new Stack<TreeNode>();
        if (rootNode != null) {
            stack.push(rootNode);
            while (!stack.isEmpty()) {
                TreeNode node = stack.pop();
                System.out.println(node);
                if (node.getRight() != null) {
                    stack.push(node.getRight());
                }
                if (node.getLeft() != null) {
                    stack.push(node.getLeft());
                }
            }
        }
    }
    
    /**
     * 中序遍历,非递归实现
     * 
     * @param rootNode
     */
    public void inOrderTreeWalkNonrecursive(TreeNode rootNode) {
    
        Stack<TreeNode> stack = new Stack<TreeNode>();
        while (rootNode != null || !stack.isEmpty()) {
            if (rootNode != null) {
                stack.push(rootNode);
                rootNode = rootNode.getLeft();
            }
            else {
                rootNode = stack.pop();
                System.out.println(rootNode);
                rootNode = rootNode.getRight();
            }
        }
    }
    
    /**
     * 后续遍历,非递归实现
     * 
     * @param rootNode
     */
    public void postOrderTreeWalkNonrecursive1(TreeNode rootNode) {
    
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode prev = null;
        TreeNode curr = null;
        
        if (rootNode != null) {
            stack.push(rootNode);
        }
        while (!stack.isEmpty()) {
            curr = stack.peek();
            if (prev == null || prev.getLeft() == curr || prev.getRight() == curr) {
                if (curr.getLeft() != null) {
                    stack.push(curr.getLeft());// 压左孩子
                }
                else if (curr.getRight() != null) {
                    stack.push(curr.getRight());// 压右孩子
                }
            }
            else if (curr.getLeft() == prev) {
                if (curr.getRight() != null) {
                    stack.push(curr.getRight());// 压右孩子
                }
            }
            else {
                System.out.print(curr);// 遍历输出
                stack.pop();
            }
            prev = curr;
        }
    }
    
    /**
     * 层序遍历
     * 
     * @param rootNode
     */
    public void levelOrderTreeWalk(TreeNode rootNode) {
    
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        TreeNode node = null;
        if (rootNode != null) {
            queue.offer(rootNode);
        }
        while (!queue.isEmpty()) {
            node = queue.poll();
            System.out.println(node);
            if (node.getLeft() != null) {
                queue.offer(node.getLeft());
            }
            if (node.getRight() != null) {
                queue.offer(node.getRight());
            }
        }
    }
    
    /**
     * 递归查找节点
     * 
     * @param node
     * @param key
     * @return
     */
    public TreeNode treeSearch(TreeNode node, int key) {
    
        if (node == null || key == node.getKey()) {
            return node;
        }
        if (key > node.getKey())
            return treeSearch(node.getRight(), key);
        else
            return treeSearch(node.getLeft(), key);
    }
    
    /**
     * 非递归查找节点
     * 
     * @param node
     * @param key
     * @return
     */
    public TreeNode treeSearchNonrecursive(TreeNode node, int key) {
    
        while (node != null && node.getKey() != key) {
            if (key > node.getKey())
                node = node.getRight();
            else
                node = node.getLeft();
        }
        return node;
    }
    
    /**
     * 找到以root为根节点的最大节点
     * @param root
     * @return
     */
    public TreeNode getMaxNode(TreeNode root) {
    
        while (root != null) {
            root = root.getRight();
        }
        return root;
    }
    
    /**
     * 找到以root为根节点的最小节点
     * @param root
     * @return
     */
    public TreeNode getMinNode(TreeNode root) {
    
        while (root != null) {
            root = root.getLeft();
        }
        return root;
    }
    
    /**
     * 获取一个节点的后继节点
     * @param node
     * @return
     */
    public TreeNode treeSuccessor(TreeNode node) {
    
        if (node != null && node.getRight() != null)
            return getMinNode(node.getRight());
        TreeNode tmpNode = node.getParent();
        while (tmpNode != null && node == tmpNode.getRight()) {
            node = tmpNode;
            tmpNode = tmpNode.getParent();
        }
        return tmpNode;

    }

 /**
     * 获取一个节点的前驱节点
     * @param node
     * @return
     */
    public TreeNode treePredecessor(TreeNode node) {
    
        if (node.getLeft() != null) {
            return getMaxNode(node.getLeft());
        }
        
        TreeNode tmpNode = node.getParent();
        while (tmpNode != null && node == tmpNode.getLeft()) {
            node = tmpNode;
            tmpNode = tmpNode.getParent();
        }
        return tmpNode;
    }

      
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值