This Leetcode & CTCI -- Day 7

本文详细解析了如何将已排序数组和已排序链表转换为平衡二叉搜索树(BST),并提供了具体的Java代码实现。通过中间元素作为根节点,左侧元素作为右子树,右侧元素作为左子树,实现数组到BST的高效转换。同时,介绍了一种从链表中获取中间节点的方法,用于构建平衡BST。

Question 1.

Convert Sorted Array to Binary Search Tree

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

Remember the middle index value should be the first node, while the left-side array be the node.right part and the right-side array be the node.left part. 
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums.length == 0)
            return null;
        return sortedArrayToBST(nums, 0, nums.length-1);
    }
    
    public TreeNode sortedArrayToBST(int[] nums, int smallIndex, int largeIndex){
        if (smallIndex > largeIndex)
            return null;
        int mid = (smallIndex + largeIndex)/2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = sortedArrayToBST(nums, smallIndex, mid-1);
        root.right = sortedArrayToBST(nums, mid+1, largeIndex);
        return root;
    }
}

 

 

Question 2

Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

This is more direct solution, form bottom to top and find the middle node to be the root and then assign the root.left and root.right. One big difference between this problem to the above one is the linklist cannot directly get the middle node out but need to do recursive to get the middle one. So actually it store the from the first value to end, instead of getting the middle one firstly.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    static ListNode head;
    public TreeNode sortedListToBST(ListNode head) {
        if (head == null)
            return null;
        this.head = head;
        return sortedListToBST(0, getSize(head)-1);
    }
    
    public TreeNode sortedListToBST( int smallIndex, int largeIndex){
        if (smallIndex > largeIndex)
            return null;
        int middle = (smallIndex + largeIndex) / 2;
        TreeNode left = sortedListToBST(smallIndex, middle-1);
        TreeNode root = new TreeNode(head.val);
        root.left = left;
        head = head.next;
        root.right = sortedListToBST(middle+1, largeIndex);
        return root;
    }
    
    public int getSize(ListNode head){
        int len = 0;
        while (head != null){
            head = head.next;
            len ++;
        }
        return len;
    }
}

 Question 3

Minimum Depth of Binary Tree

 Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

 This problem is done before with DFS function. Here I used BFS to do it again. For BFS, remember to use a queue to keep all nodes' siblings.

public class Solution {
    public int minDepth(TreeNode root) {
        if (root == null)
            return 0;
        int depth = 1;
        ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
        queue.add(root);
        int curnum = 1;
        int nextnum = 0;
        while (!queue.isEmpth()){
            TreeNode cur = queue.poll();
            curnum--;
            if (cur.left == null && cur.right == null)
                return depth;
            if (cur.left != null){
                queue.add(cur.left);
                nextNum ++;
            }
            if (cur.right != null){
                queue.add(cur.right);
                nextnum ++;
            }
            if (curnum == 0){
                curnum = nextnum;
                nextnum = 0;
                depth++;
            }
        }
        return depth;
    }
}

 Another BSF code I found.

public int minDepth(TreeNode root) {
        // BFS
        if (root == null) {
            return 0;
        }
        
        int res = 1;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size-- > 0) {
                TreeNode node = queue.poll();
                if (node.left == null && node.right == null) {
                    return res;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            res++;
        }
        
        return res;
    }

 

 

 

 

posted on 2015-07-14 22:20 Timo66 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/timoBlog/p/4646754.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值