DLL ro BST BST to DLL

已写bst to dll


class Test{
    /**
     * @param root: The root of tree
     * @return: the head of doubly list node
     */
    static class TreeNode {
      public int val;
      public TreeNode left, right;
      public TreeNode(int val) {
          this.val = val;
          this.left = this.right = null;
      }
    }

    public static TreeNode bstToDoublyList(TreeNode root) {  
        TreeNode dummy = new TreeNode(0);
        TreeNode prev = dummy;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode curt = root;
        while (curt != null){
            stack.push(curt);
            curt = curt.left;
        }
        while (!stack.isEmpty()){
            curt = stack.pop();
            prev.right = curt;
            curt.left = prev;
            prev = curt;
            curt = curt.right;
            while (curt != null){
                stack.push(curt);
                curt = curt.left;
            }
        }
        // if circular, add:
        // prev.right = dummy.right;
        // dummy.right.left = prev;
        return dummy.right;
    }

    static void printList(TreeNode node) 
    {
        while (node != null) 
        {
            System.out.print(node.val + " ");
            node = node.right;
        }
    }
  
    /* Driver program to test above functions*/
    public static void main(String[] args) 
    {

       //      20
       //    /   \
       //   15    30
       //  / \   / 
       // 10 18  25 
        TreeNode root = new TreeNode(20);
        root.left = new TreeNode(15);
        root.right = new TreeNode(30);
        root.left.left = new TreeNode(10);
        root.left.right = new TreeNode(18);
        root.right.left = new TreeNode(25);
  
        // Convert to DLL
        TreeNode head = bstToDoublyList(root);
  
        // Print the converted list
        printList(head);
    }
}

dll to bst

//convert sorted array to BST time O(n) space o(n) stack space o(nlogn)
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null || nums.length == 0){
            return null;
        }        
        return helper(nums, 0, nums.length - 1);
    }
    
    private TreeNode helper(int[] nums, int left, int right){
        if (left > right){
            return null;
        }
        int mid = left + (right - left) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = helper(nums, left, mid - 1);
        root.right = helper(nums, mid + 1, right);
        return root;
    }
}


//109.Convert Sorted List to Binary Search Tree  time: O(nLogn)
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if (head == null){
            return null;
        }
        return toBST(head, null);
    }
    
    private TreeNode toBST(ListNode head, ListNode tail){
        if (head == tail){
            return null;
        }
        ListNode slow = head;
        ListNode fast = head;
        while (fast != tail && fast.next != tail){
            slow = slow.next;
            fast = fast.next.next;
        }
        TreeNode root = new TreeNode(slow.val);
        root.left = toBST(head, slow);
        root.right = toBST(slow.next, tail);
        return root;
    }
}

//inplace (using original DLL and don't creat new TreeNode)convert (circular) doubly linkedlist to balanced bst, O(n) time, O(logn) space
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: a tree node
     */
    private ListNode curr;
    
    public ListNode sortedListToBST(ListNode head) {
        if (head == null) {
            return head;
        }
        // 1.if it's a circular list that tail connects to head
        // curr.prev.next = null;
        // curr.prev = null;
        // 2.if it's a circular list that tail connects to any node
        // ListNode tail = getTail(head);
        // tail.next.prev = null;
        // tail.next = null;
        // after cutting the cycle, we can count nodes and build trees
        curr = head;
        int size = getSize(head);
        return buildTree(size);
    }
    
    private int getSize(ListNode head) {
        int size = 0;
        while (head != null) {
            size++;
            head = head.next;
        }
        return size;
    }
    
    private ListNode buildTree(int size) {
        if (size <= 0) {
            return null;
        }
        ListNode left = buildTree(size / 2);
        ListNode root = curr;//curr is the root of these two subtrees
        curr = curr.next;
        ListNode right = buildTree(size - 1 - size / 2);
        root.prev = left;
        root.next = right;
        return root;
    }
    
    //this method is almost same as Linked List Cycle 2
    public ListNode getTail(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != slow) {
            if (fast == null || fast.next == null) {
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        while (head != slow.next) {
            head = head.next;
            slow = slow.next;
        }
        return slow;//return the tail
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • [TOC] 一. 简介 1.1 C++两种库文件 lib包含了函数所在的dll文件和文件中函数位置的信息(入口),...
    ass_kicker阅读 11,122评论 0 8
  • 总结类型: 完全子树(#222) BST(左右子树值的性质,注意不仅要满足parent-child relatio...
    __小赤佬__阅读 3,994评论 0 0
  • php.ini设置,上传大文件: post_max_size = 128Mupload_max_filesize ...
    bycall阅读 11,791评论 3 64
  • 一、温故而知新 1. 内存不够怎么办 内存简单分配策略的问题地址空间不隔离内存使用效率低程序运行的地址不确定 关于...
    SeanCST阅读 12,386评论 0 27
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,356评论 0 33

友情链接更多精彩内容