이진 검색 트리

19679 단어
Populating next right pointer
TC: O(N), 여기서 N은 아니오입니다. 트리의 노드 수

import java.util.*;
public class Solution {
    public static void connectNodes(BinaryTreeNode<Integer> root) {
        // Write your code here.
        // we will use level order traversal for this
        Queue<BinaryTreeNode<Integer>> q = new LinkedList<>();
        if(root==null) return;
        q.add(root);
        while(!q.isEmpty()){
            int size = q.size();
            BinaryTreeNode<Integer> prev = null;
            for(int i = 0;i<size;i++){
                BinaryTreeNode<Integer> node = q.remove();
                node.next= prev;
                prev = node;
                if(node.right!=null) q.add(node.right);
                if(node.left!=null)q.add(node.left);

            }
        }
    }
}


Convert Sorted Array to binary search tree

요소가 오름차순으로 정렬된 정수 배열 nums가 주어지면 이를 높이 균형 이진 검색 트리로 변환합니다.
TC: o(logn) 배열을 이진 검색 알고리즘과 동일하게 만드는 두 개의 동일한 절반으로 나누기 때문입니다.


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return createBST(0,nums.length-1,nums);
    }
    public TreeNode createBST(int start, int end,int nums[]){
        if(start > end) return null;
        int mid  = start + (end-start)/2;
        TreeNode node = new TreeNode(nums[mid]);
        node.left = createBST(start,mid-1,nums);
        node.right = createBST(mid+1,end,nums);
        return node;
    }
}


Construct preorder traversal from binary search tree
TC: O(nlogn) + O(n), 여기서 nlogn은 배열 정렬,

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode bstFromPreorder(int[] preorder) {
        int index =0;
        int sortedArray[] = new int[preorder.length];
        Queue<Integer> q = new LinkedList<>();
        for(int i =0;i< sortedArray.length;i++){
             sortedArray[i] = preorder[i];
             q.add(preorder[i]);
        }
        Arrays.sort(sortedArray);
        return createBst(0,sortedArray.length-1,q,sortedArray);

    }
    public TreeNode createBst(int start, int end, Queue<Integer> q,int[] sortedArray){
        if(start > end) return null;
        int rootVal = q.remove();
        TreeNode node = new TreeNode(rootVal);
        int mid = binarySearch(start,end,rootVal,sortedArray);
        node.left = createBst(start,mid-1,q,sortedArray);
        node.right = createBst(mid+1,end,q,sortedArray);
        return node;
    }
    public int binarySearch(int start, int end,int target, int[] arr){
        if(start > end) return -1;
        int mid  = start + (end-start)/2;
        if(arr[mid] == target) return mid;
        if(arr[mid] > target){
            return binarySearch(start,mid-1, target, arr);
        }
        return binarySearch(mid+1, end, target,arr);
    }


최적화된 솔루션:
TC: O(n)인 O(3N)

//for more idea see this https://www.youtube.com/watch?v=UmJT3j26t1I
class Solution {
    public TreeNode bstFromPreorder(int preorder[]){
        return generateBST(preorder, new int[]{0},Integer.MAX_VALUE); //0 indicates the current pointer of the element that needs to be inserted
        //Integer.MAX_VALUE is max bound
    }
    public TreeNode generateBST(int[] pre,int pointer[], int bound){
        if(pointer[0] > pre.length-1 || pre[pointer[0]] > bound) return null;
        TreeNode node = new TreeNode(pre[pointer[0]++]);// value at pointer has been added to the tree, now move to next value int the array
        node.left = generateBST(pre,pointer,node.val); // now node.val will become bound for all the 
        // elements to the left of node, as they can't be equal to or greater than node.val
        node.right = generateBST(pre,pointer,bound);//for the right subtree bound will remain same
        return node;
    }

좋은 웹페이지 즐겨찾기