zoukankan      html  css  js  c++  java
  • 二叉树--转换二叉树(leetcode 108,leetcode 109)

    基础知识

    1. 二叉树搜索树BST的中序遍历是升序序列,所以108和109中给出的数组和链表的顺序即为BST中序遍历的顺序

    2. 给定BST的中序序列,肯定没法唯一确定BST的

    3. 在2的基础上要求BST平衡,也是没法唯一确定BST的


    leetcode 108

        public TreeNode sortedArrayToBST(int[] nums) {
            return helper(nums, 0, nums.length - 1);
        }
    
        public TreeNode helper(int[] nums, int left, int right){
            if (left > right){
                return null;
            }
            int mid = (left + right) / 2;
            TreeNode root = new TreeNode(nums[mid]);
            root.left = helper(nums, left, mid - 1);
            root.right = helper(nums, mid + 1, right);
            return root;
        }
    

    时间复杂度:O(N),数组中每个元素都要访问一次
    空间复杂度:O(LOGN),二分法的递归栈


    leetcode 109

    直接用链表做

        public TreeNode sortedListToBST(ListNode head) {
    
            if (head == null){
                return null;
            }
    
    
            ListNode fast = head;
            ListNode slow = head;
            ListNode pre = head;
            while (fast != null && fast.next != null){
                pre = slow;
                fast = fast.next.next;
                slow = slow.next;
            }
    
            ListNode mid = slow;
            ListNode rightPart = mid.next;
            pre.next = null;
            TreeNode root = new TreeNode(mid.val);
    
            if (head == mid){
                return root;
            }
    
            root.left = sortedListToBST(head);
            root.right = sortedListToBST(rightPart);
            return root;
        }
    

    时间复杂度:O(Nlogn)
    空间复杂度:O(logN)

    也可以先转换成数组,然后用108的解法做,相当于用空间换时间。

  • 相关阅读:
    !ps之前一次执行的内容
    shortcut switch in terminal start pos & end pos
    百度词典搜索_dress code
    修杰楷_百度百科
    红米让夏新没活路了,
    绝杀600元以下智能手机的夏新小V二代-专栏-速途网
    李宗瑞_百度百科
    监制_百度百科
    文件上传~Uploadify上传控件
    知方可补不足~CSS中的几个伪元素
  • 原文地址:https://www.cnblogs.com/swifthao/p/13307819.html
Copyright © 2011-2022 走看看