Code Interview Note
  • 0. Introduction
  • 1. Basic
    • Python Basic
    • Java Basic
    • Primitive Type
    • Basic Question
    • Number
  • 2. Array and Numbers
    • General
    • TwoSum
    • Buy and Sell Stock
    • SubArray
      • SubArray + HashMap
    • Sliding Window
      • Sliding Window At Most Problem
    • Word Break
    • Passes Problem
    • Majority Element
    • Partition Array
    • Sort Colors
    • Anagram
    • Ugly Number
    • TwoPointer
    • Swipe Line
    • Calculator
    • Sudoku
  • 2.1 String
    • String
    • Palindrome
    • Parentheses
    • Decode String
    • Calculator
    • Abbreviation
  • 3. Linkedlist
    • Dummy Node
    • Double Pointers
  • 4. Stack and Queue
    • General
    • Increase/Decrease Stack
  • 5. Binary Search
    • General
    • BS on result
    • Save the half which has result
    • Rotated Sorted Array
    • Split Array Largest Sum
  • 6. Binary Tree
    • General
    • Path Sum
    • Lowest Common Ancestor
    • BST
    • Convert
    • Traverse
    • Valid Ordered Tree
    • Construct Binary Tree
    • Tree depth and width
    • Vertical Order Traverse
  • 7. Heap
    • Geneal
    • TopK
  • 8. Simulation
    • General
    • Read4
    • Encode Decode
    • LRU/LFU
    • Robot
    • GetRandom O(1)
    • Probability
  • 9. DFS
    • Backtrack
    • General
    • Subset
    • Permutation
    • Combination
  • 10. HashTable
    • General
  • 11. Sort
    • General
  • 12. Recursion
    • General
  • 13. Dynamic Programming
    • Graph
    • General
    • Coordinate
    • Double Sequence
    • Longest Common Subsequence
    • Rolling Array
    • House Robber
    • Backpack
    • Memorization
    • Diagonal
  • 14. BFS
    • General
    • Number of Islands
    • The Maze
  • 15. Graph
    • Shortest Path
    • Undirected Graph
    • Topology Sort
    • Word Ladder
    • Tarjan's Algo
  • 16. Divide & Conquer
    • General
  • 17. UnionFind
    • General
    • Grouping
  • 18. Trie
    • General
    • Word Square
  • 19. Company Summary
    • Oracle
    • Amazon
      • DP
    • Google
    • Hackerrank
    • LinkedIn
  • 20. Design
  • 21. Math
  • Behavior Question
  • Internet
  • OS
Powered by GitBook
On this page
  • 114 Flatten Binary Tree to Linked List
  • 106t Convert Sorted LinkedList to Balanced BST
  • 426 Convert BST to double linked list

Was this helpful?

  1. 6. Binary Tree

Convert

PreviousBSTNextTraverse

Last updated 4 years ago

Was this helpful?

114 Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

def flatten(self, root: TreeNode) -> None:
    self.preNode = None
    
    def helper(node):
        nonlocal preNode
        if not node: return None
        helper(node.right)
        helper(node.left)
        
        node.right = preNode
        node.left = None
        preNode = node
        
    helper(root)
def flatten(self, root: TreeNode) -> None:
    if not root: return
    
    node = root
    
    while node:
        if node.left: 
            rightMost = node.left

            while rightMost.right:
                rightMost = rightMost.right
            
            rightMost.right = node.right
            node.right = node.left
            node.left = None
            
        node = node.right
        

106t Convert Sorted LinkedList to Balanced BST

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

  • Divide and Conquer

public TreeNode sortedListToBST(ListNode head) {
    if (head == null){
        return null;
    }
    return BSTHelper(head, null);
}

public TreeNode BSTHelper(ListNode head, ListNode tail) {
    if (head == tail){
        return null;
    }

    // let slow goes to middle point
    ListNode slow = head, fast = head;
    while(fast.next != tail && fast.next.next != tail){
        slow = slow.next;
        fast = fast.next.next;
    }
    TreeNode left = BSTHelper(head, slow);
    TreeNode right = BSTHelper(slow.next, tail);

    TreeNode root = new TreeNode(slow.val);
    root.left = left;
    root.right = right;
    return root;
}

426 Convert BST to double linked list

Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list.並且首尾相連

private Node pre;
public Node treeToDoublyList(Node root) {
    if(root == null) return null;

    Node dummy = new Node(0);
    pre = dummy;
    helper(root);

    // now the "pre" is the tail node
    // connect head and tail
    pre.right = dummy.right;
    dummy.right.left = pre;

    return dummy.right;
}

private void helper(Node node){
    if(node == null) return;
    helper(node.left);
    pre.right = node; // 同時將dummy.right 指向 head node
    node.left = pre;
    pre = node; // 這裏dummy 不跟著變化
    helper(node.right);
}
"""
inorder traverse
current node and tail node 之間更新
需要兩個pointer紀錄head and tail
最後head and tail連起來
"""
class Solution:
    def treeToDoublyList(self, root: 'Node') -> 'Node':
        if not root: return None
        self.head, self.tail = None, None
        self.helper(root)
        self.tail.right = self.head
        self.head.left = self.tail
        return self.head
      
    def helper(self, node):
        if not node: return
        
        self.helper(node.left)
        
        if self.tail:
            self.tail.right = node
            node.left = self.tail
        else:
            # 只會更新一次, 在head的時候
            self.head = node
        self.tail = node
        self.helper(node.right)