MrainW's Home

All things come to those who wait!

0%

Question

You are given the root of a binary tree containing digits from 0 to 9 only.

Each root-to-leaf path in the tree represents a number.

  • For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.

Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.

A leaf node is a node with no children.

https://leetcode.com/problems/sum-root-to-leaf-numbers/

Solution

  • Solution1 – DFS, top down
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
int sum = 0;
public int sumNumbers(TreeNode root) {
if (root == null)
return 0;
dfs(root, 0);
return sum;
}
private void dfs(TreeNode root, int num){
num = num * 10 + root.val;
if (root.left == null && root.right == null){
sum += num;
return;
}
if (root.left != null) dfs(root.left, num);
if (root.right != null) dfs(root.right, num);
}
}
1
2
3
4
5
top down general steps:
1. base case(leaf)
2. 利用父问题传下来的值做计算 num = 10*num + num
3. 额外操作
4. 把值传给子问题递归 dfs()

Complexity:

Time complexity: O(n)

Space complexity: O(h)

Question

https://leetcode.com/problems/binary-tree-maximum-path-sum/

Solution

  • Solution1 – DFS, bottom up
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
int maxvalue = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
dfs(root);
return maxvalue;
}
public int dfs(TreeNode node){
if (node == null) return 0;
int left = dfs(node.left);
int right = dfs(node.right);
left = left < 0 ? 0 : left;
right = right < 0 ? 0 : right;
maxvalue = Math.max(maxvalue, left + right + node.val);
return Math.max(left, right) + node.val;
}
}
1
2
3
4
5
6
bottom up general steps:
1. Base case
2. 向子问题要答案
3. 利用子问题构建当前答案
4. 额外操作
5. 返回答案给父问题

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Question

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

https://leetcode.com/problems/maximum-depth-of-binary-tree/

Solution

  • Solution1 – DFS, bottom up
1
2
3
4
5
6
7
8
class Solution {
public int maxDepth(TreeNode root) {
if (root == null){
return 0;
}
return 1 + Math.max(maxDepth(root.left),maxDepth(root.right));
}
}
1
2
3
4
5
6
bottom up general steps:
1. Base case
2. 向子问题要答案
3. 利用子问题构建当前答案
4. 额外操作
5. 返回答案给父问题

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Question

  1. Given the root of a binary tree, determine if it is a valid binary search tree (BST).

    A valid BST is defined as follows:

    • The left subtree of a node contains only nodes with keys less than the node’s key.
    • The right subtree of a node contains only nodes with keys greater than the node’s key.
    • Both the left and right subtrees must also be binary search trees.

https://leetcode.com/problems/validate-binary-search-tree/

Solution

  • Solution1 – DFS, bottom up
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

private boolean isValidBST(TreeNode root, long minVal, long maxVal) {
if (root == null) return true;
if (root.val >= maxVal || root.val <= minVal) return false;
return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal);
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Question

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

  1. Search for a node to remove.
  2. If the node is found, delete the node.

https://leetcode.com/problems/delete-node-in-a-bst/

Solution

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) return null;
if(key < root.val) root.left = deleteNode(root.left, key);
else if(key > root.val) root.right = deleteNode(root.right, key);
else if(root.left == null) return root.right;
else if(root.right == null) return root.left;
else{
root.val = findMin(root.right);
root.right = deleteNode(root.right, root.val);
}
return root;
}
private int findMin(TreeNode node){
while(node.left != null) node = node.left;
return node.val;
}
}

Complexity:

Time complexity: O(logn)

Space complexity: O(H)

Question

Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place.

You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.

We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.

https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/

Example 1:

1
2
3
4
Input: root = [4,2,5,1,3]
Output: [1,2,3,4,5]

Explanation: The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship.

Example 2:

1
2
3
Input: root = [2,1,3]
Output: [1,2,3]

Solution

  • Solution1 – recursive
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
Node pre = null, head = null;
public Node treeToDoublyList(Node root) {
if (root == null) return root;
inorderTraversal(root);
head.left = pre;
pre.right = head;
return head;
}
private void inorderTraversal(Node root){
if(root == null) return;
inorderTraversal(root.left); //left
if(head == null) head = root;
if(pre != null) pre.right = root; //root
root.left = pre;
pre = root;
inorderTraversal(root.right); //right
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Question

Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.

Example 1:

1
2
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]

Example 2:

1
2
Input: inorder = [-1], postorder = [-1]
Output: [-1]

Solution

  • Solution1 – postorder traversal, inorder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int[] inorder;
int[] postorder;
int N;
Map<Integer, Integer> inMap = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
this.inorder = inorder;
this.postorder = postorder;
N = inorder.length;
for (int i = 0; i < N; i++) inMap.put(inorder[i], i);
return helper(0, N - 1, 0, N - 1);
}
public TreeNode helper(int inStart, int inEnd, int postStart, int postEnd){
if (inStart > inEnd) return null;
TreeNode root = new TreeNode(postorder[postEnd]);
int inIndex = inMap.get(root.val);
int rightTreeSize = inEnd - inIndex;
root.left = helper(inStart, inIndex - 1, postStart, postEnd - rightTreeSize -1);
root.right = helper(inIndex + 1, inEnd, postEnd - rightTreeSize, postEnd -1);
return root;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Question

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

Example 1:

1
2
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]

Example 2:

1
2
Input: preorder = [-1], inorder = [-1]
Output: [-1]

Solution

  • Solution1 – preorder traversal, inorder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int[] preorder;
int[] inorder;
int preOrderIndex;
Map<Integer, Integer> treeMap = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
this.preorder = preorder;
this.inorder = inorder;
this.preOrderIndex = 0;
int N = preorder.length;
for (int i = 0; i < N; i++) treeMap.put(inorder[i], i);
return helperbulid(0, N-1);
}
public TreeNode helperbulid(int instart, int inend){
if(instart > inend) return null;
TreeNode root = new TreeNode(preorder[preOrderIndex++]);
int index = treeMap.get(root.val);
root.left = helperbulid(instart, index - 1);
root.right = helperbulid(index + 1, inend);
return root;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Question

Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.

It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.

A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.

A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.

Example 1:

1
2
Input: preorder = [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]

Example 2:

1
2
Input: preorder = [1,3]
Output: [1,null,3]

Solution

  • Solution1 – preorder traversal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
int index, N;
int[] preorder;
public TreeNode helper(int lower, int upper){
if (index == N) return null;
int val = preorder[index];
if (val < lower || val > upper) return null;
index ++;
TreeNode root = new TreeNode(val);
root.left = helper(lower, val);
root.right = helper(val, upper);
return root;
}
public TreeNode bstFromPreorder(int[] preorder) {
this.preorder = preorder;
N = preorder.length;
return helper(Integer.MIN_VALUE, Integer.MAX_VALUE);
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Question

Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.

The encoded string should be as compact as possible.

Example 1:

1
2
Input: root = [2,1,3]
Output: [2,1,3]

Example 2:

1
2
Input: root = []
Output: []

Solution

  • Solution1 – preorder traversal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Codec {

// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) return "";
String res = String.valueOf(root.val);
if (root.left != null) res += "," + serialize(root.left);
if (root.right != null) res += "," + serialize(root.right);
return res;
}

// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.isEmpty()) return null;
Queue<String> q = new LinkedList<>(Arrays.asList(data.split(",")));
return deserialize(q, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
public TreeNode deserialize(Queue<String> q, int lower, int upper){
if (q.isEmpty()) return null;
String s = q.peek();
int val = Integer.parseInt(s);
if (val < lower || val > upper) return null;
q.poll();
TreeNode root = new TreeNode(val);
root.left = deserialize(q, lower, val);
root.right = deserialize(q, val, upper);
return root;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)