构建查找二叉树

查找二叉树的特点是根节点的左孩子都小于根节点,右孩子都大于根节点,可以联想到二分查找。

构造查找二叉树的Java实现如下:

public class SearchBinaryTree {
    private TreeNode root;
    public class TreeNode{
        private int key;
        private int data;
        private TreeNode leftChild;
        private TreeNode rightChild;
        private TreeNode parent;
        public TreeNode(int key, int data) {
            super();
            this.key = key;
            this.data = data;
            this.leftChild=null;
            this.rightChild=null;
            this.parent=null;
        }

        public int getKey() {
            return key;
        }

        public void setKey(int key) {
            this.key = key;
        }

        public int getData() {
            return data;
        }

        public void setData(int data) {
            this.data = data;
        }

        public TreeNode getLeftChild() {
            return leftChild;
        }

        public void setLeftChild(TreeNode leftChild) {
            this.leftChild = leftChild;
        }

        public TreeNode getRightChild() {
            return rightChild;
        }

        public void setRightChild(TreeNode rightChild) {
            this.rightChild = rightChild;
        }

        public TreeNode getParent() {
            return parent;
        }

        public void setParent(TreeNode parent) {
            this.parent = parent;
        }
    }

    /**
     * 构建查找二叉树
     */
    public TreeNode put(int data){
        TreeNode node=null;
        TreeNode parent=null;
        if (root==null){
            node=new TreeNode(0,data);
            root=node;
            return node;
        }
        node=root;
        while(node!=null){
            parent=node;
            if (data<node.data){
                node=node.leftChild;
            }else if(data>node.data){
                node=node.rightChild;
            }else{
                return node;
            }
        }
        node=new TreeNode(0,data);
        if (data<parent.data){
            parent.leftChild=node;
        }else{
            parent.rightChild=node;
        }
        return node;
    }

    /**
     * 中序遍历查找二叉树判断构建二叉树是否正确
     */
    public void midOrder(TreeNode node){
        if (node==null){
            return ;
        }
        midOrder(node.leftChild);
        System.out.println("当前节点为:" + node.data);
        midOrder(node.rightChild);
    }
    public static void main(String[] args){
        SearchBinaryTree searchBinaryTree=new SearchBinaryTree();
        int[] array=new int[]{50,30,20,44,88,33,87,16,77};
        for (int arr:array) {
            searchBinaryTree.put(arr);
        }
        searchBinaryTree.midOrder(searchBinaryTree.root);
    }
}
    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/yangmingtia/article/details/81980284
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞