Convert Sorted Array to Binary Search Tree——LeetCode

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

题目大意:给定一个升序序列的数组,将其转换为二叉搜索树。

解题思路:数组中间元素是根元素,根元素将数组划分为两部分,两个部分的中心元素分别为根元素的左右孩子,依次递推。。。可用迭代或递归来做。

解法一(迭代):迭代需要自己额外记录下标

    public TreeNode sortedArrayToBST(int[] num) {
        if (num == null || num.length == 0) {
            return null;
        }
        if (num.length == 1) {
            return new TreeNode(num[0]);
        }
        Deque<Pair> queue = new ArrayDeque<>();
        TreeNode root = new TreeNode(num[(num.length - 1) / 2]);
        queue.add(new Pair(0, num.length - 1, root));
        while (!queue.isEmpty()) {
            Pair pair = queue.poll();
            int pre = pair.pre;
            int post = pair.post;
            int curr = (post + pre) / 2;
            TreeNode tNode = pair.node;
            if (curr > pre) {
                TreeNode left = new TreeNode(num[(curr - 1 + pre) / 2]);
                tNode.left = left;
                queue.add(new Pair(pre, curr - 1, left));
            }
            if (post > curr) {
                TreeNode right = new TreeNode(num[(post + curr + 1) / 2]);
                tNode.right = right;
                queue.add(new Pair(curr + 1, post, right));
            }
        }
        return root;
    }

    private static class Pair {
        int pre;
        int post;
        TreeNode node;

        public Pair(int pre, int post, TreeNode node) {
            this.pre = pre;
            this.post = post;
            this.node = node;
        }
    }

 

解法二(递归):

    public TreeNode sortedArrayToBST(int[] num) {
        if (num == null || num.length == 0) {
            return null;
        }
        TreeNode root = helper(0, num.length - 1, num);
        return root;
    }

    private TreeNode helper(int low, int high, int[] num) {
        if (low > high) {
            return null;
        }
        int mid = (low + high) / 2;
        TreeNode node = new TreeNode(num[mid]);
        node.left = helper(low, mid - 1, num);
        node.right = helper(mid + 1, high, num);
        return node;
    }

 

posted @ 2015-04-20 21:28  丶Blank  阅读(136)  评论(0编辑  收藏  举报