二叉排序树的建立和遍历(java)

来源:互联网 发布:网络黑彩票代理犯法吗 编辑:程序博客网 时间:2024/05/18 02:09

也是个经典的面试题,要求建立二叉排序树同时实现树的遍历,其实不难,直接上代码吧


树节点定义:

class TreeNode{    int val;    TreeNode left;    TreeNode right;    TreeNode(){    }    TreeNode(int value){        this.val = value;        this.left = null;        this.right = null;    }    TreeNode(int value, TreeNode left, TreeNode right){        this.val = value;        this.left = left;        this.right = right;    }}

建立二叉排序树

public static TreeNode buildBST(int[] data){        //建立二叉排序树        //假设data中的数字是互不相同的        TreeNode root = new TreeNode(data[0]);        for(int i = 1; i < data.length; i++){            insert(root, data[i]);        }        return root;    }    private static TreeNode insert(TreeNode root, int value) {        //二叉排序树插入节点        if(root == null){            root = new TreeNode(value);        }else{            if(value <= root.val){                //插入到左子树                root.left = insert(root.left, value);            }else{                //插入到右子树                root.right = insert(root.right, value);            }        }        return root;    }

遍历验证下:
更多的树的遍历方法,参考二叉树的多种遍历方法

public static void preOrder(TreeNode root){        if(root == null){            return;        }        System.out.print(root.val + " ");        if(root.left != null){            preOrder(root.left);        }        if(root.right != null){            preOrder(root.right);        }    }

main函数:

public static void main(String[] args) {        int[] data = {3,1,2,5,0,7,9,8};        TreeNode root = Main.buildBST(data);        Main.preOrder(root);    }

当然这样生成的二叉树不是高度最小的二叉树,不过对于面试到这基本也就可以了


这篇博客说了如何建立高度最小的二叉排序树,大家参考下

0 0
原创粉丝点击