Skip to content

Commit 54de66f

Browse files
[Content Update] added two binary tree problems (patternize#31)
* added a binary tree question and fixed some solution code * fixed minor typos * added another binary tree question / fixed minor typos * fixed sidebar * added another problem under binary tree common problems * added sidebar changes * added another question * added a question to bst commmon problems / fixed minor typos * added sidebar changes * fixed typo * deleted lc450 (it was already part of bst operations) * add other languages and more solutions Co-authored-by: Carl <shikang.liu@mail.mcgill.ca>
1 parent 618c086 commit 54de66f

8 files changed

+654
-6
lines changed
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
---
2+
id: LC101
3+
title: LC101. Symmetric Tree
4+
sidebar_label: LC101. Symmetric Tree
5+
tags: ['Patterns/Tree', 'DataStructures/Tree']
6+
---
7+
8+
## Problem Description
9+
10+
Source: https://leetcode.com/problems/symmetric-tree/
11+
12+
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
13+
14+
For example, this binary tree [1, 2, 2, 3, 4, 4, 3] is symmetric:
15+
16+
```
17+
1
18+
/ \
19+
2 2
20+
/ \ / \
21+
3 4 4 3
22+
```
23+
24+
But the following [1, 2, 2, null, 3, null, 3] is not:
25+
```
26+
1
27+
/ \
28+
2 2
29+
\ \
30+
3 3
31+
```
32+
33+
## Solution
34+
35+
### High level strategy
36+
To check whether two nodes are identical, we can check the following conditions:
37+
1. If both nodes are null, then they **are the same**.
38+
2. If one of the nodes is null, then they **are not the same**.
39+
3. If the value of one node is not equal to the value of the other, then they **are not the same**.
40+
41+
To check whether a tree is symmetrical, we can simply apply the logics above to the opposite nodes on each side of the tree. That is, we compare the right child of the left child with the left child of the right child, so on and so forth. We recurse down both sides of the root node, and return true if and only if both sides return true. The time complexity of this solution is **O(n)**.
42+
43+
### Code
44+
import Tabs from '@theme/Tabs';
45+
import TabItem from '@theme/TabItem';
46+
47+
<Tabs
48+
defaultValue="js"
49+
values={[
50+
{ label: 'Javascript', value: 'js', },
51+
{ label: 'Java', value: 'java', }
52+
]
53+
}>
54+
<TabItem value="js">
55+
56+
```javascript
57+
/**
58+
* Definition for a binary tree node.
59+
* function TreeNode(val, left, right) {
60+
* this.val = (val===undefined ? 0 : val)
61+
* this.left = (left===undefined ? null : left)
62+
* this.right = (right===undefined ? null : right)
63+
* }
64+
**/
65+
66+
const isSymmetric = (root) => {
67+
if (root === null) return true;
68+
return isSame(root.left, root.right);
69+
};
70+
71+
const isSame = (node1, node2) => {
72+
if (node1 === null && node2 === null) return true;
73+
if (node1 === null || node2 === null) return false;
74+
if (node1.val !== node2.val) return false;
75+
76+
return isSame(node1.left, node2.right) && isSame(node1.right, node2.left);
77+
};
78+
```
79+
</TabItem>
80+
<TabItem value="java">
81+
82+
```java
83+
public boolean isSymmetric(TreeNode root) {
84+
return root==null || isSymmetricHelp(root.left, root.right);
85+
}
86+
87+
private boolean isSymmetricHelp(TreeNode left, TreeNode right){
88+
if(left==null || right==null)
89+
return left==right;
90+
if(left.val!=right.val)
91+
return false;
92+
return isSymmetricHelp(left.left, right.right) && isSymmetricHelp(left.right, right.left);
93+
}
94+
```
95+
</TabItem>
96+
</Tabs>
97+
98+
## Other Solutions
99+
<details>
100+
<summary>BFS Approach</summary>
101+
102+
103+
```java
104+
/**
105+
* We can also explore each level through BFS,
106+
* then iterate through all nodes in each level to see if they are a mirror
107+
* (same idea as checking if a string is a palindrome).
108+
*/
109+
110+
class Solution {
111+
public boolean isSymmetric(TreeNode root) {
112+
if (root == null) return true;
113+
Queue<TreeNode> queue = new LinkedList<>();
114+
queue.add(root);
115+
while(queue.size() > 0) {
116+
int size = queue.size();
117+
List<Integer> level = new ArrayList<>();
118+
while(size > 0) {
119+
TreeNode cur = queue.poll();
120+
if (cur == null) {
121+
level.add(null);
122+
} else {
123+
level.add(cur.val);
124+
queue.add(cur.left);
125+
queue.add(cur.right);
126+
}
127+
size--;
128+
}
129+
List<Integer> reverse = new ArrayList<>();
130+
for(int i = level.size() - 1; i >= 0; i--) {
131+
reverse.add(level.get(i));
132+
}
133+
if (!level.equals(reverse)) return false;
134+
}
135+
return true;
136+
}
137+
}
138+
```
139+
</details>

‎docs/QuestionBank/Leetcode/103. Binary Tree Zigzag Level Order Traversal.md‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,15 @@ Our strategy to solve this problem will be to conduct a breadth-first search. Ho
3939

4040
### Code
4141
```javascript
42+
/**
43+
* Definition for a binary tree node.
44+
* function TreeNode(val, left, right) {
45+
* this.val = (val===undefined ? 0 : val)
46+
* this.left = (left===undefined ? null : left)
47+
* this.right = (right===undefined ? null : right)
48+
* }
49+
**/
50+
4251
const zigzagLevelOrder = (root) => {
4352
let result = [];
4453

@@ -64,9 +73,8 @@ const zigzagLevelOrder = (root) => {
6473
};
6574
```
6675

67-
68-
6976
## Other Solutions
77+
- We can potentially use a deque, insert it at head for odd levels, and tail for even levels
7078

7179
import Tabs from '@theme/Tabs';
7280
import TabItem from '@theme/TabItem';
@@ -152,4 +160,4 @@ class Solution(object):
152160
return traversal
153161
```
154162
</TabItem>
155-
</Tabs>
163+
</Tabs>
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
---
2+
id: LC108
3+
title: LC108. Convert Sorted Array to Binary Search Tree
4+
sidebar_label: LC108. Convert Sorted Array to Binary Search Tree
5+
tags: ['Patterns/Tree', 'DataStructures/Tree']
6+
---
7+
8+
## Problem Description
9+
10+
Source: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
11+
12+
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. A height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
13+
14+
For example:
15+
Given the sorted array: [-10, -3, 0, 5, 9], return the following tree:
16+
```
17+
0
18+
/ \
19+
-3 9
20+
/ /
21+
-10 5
22+
```
23+
24+
## Solution
25+
26+
### High level strategy
27+
To ensure that both sides of the tree has an equal amount of nodes, and to maintain the binary search tree invariant, we must always choose the middle element of the input array as our root node. After setting the root node of the tree, we split the input array in two sub-arrays to repeat the aforementioned logic. The left sub-array will start from the beginning of the array up to the index of the middle node. The right sub-arry will start from the index after the middle node, up to the end of the array. The middle element of every sub-array will always be the root node of every subtree.
28+
29+
For example:
30+
```
31+
Input: [1, 2, 3, 4, 5, 6, 7, 8, 9];
32+
Output: [5] ---> root: [5], left: [1, 2, 3, 4], right: [6, 7, 8, 9];
33+
/ \
34+
[3] [7] ---> root: [3], left: [1, 2], right: [4];
35+
/ \ / \ root: [7], left: [6], right: [8, 9];
36+
[1] [4] [6] [8] ---> root: [1], left: null, right[2];
37+
\ \ root: [8], left: null, right[9];
38+
[2] [9]
39+
```
40+
41+
The time and space complexity of this solution are both **O(n)**.
42+
43+
### Code
44+
import Tabs from '@theme/Tabs';
45+
import TabItem from '@theme/TabItem';
46+
47+
<Tabs
48+
defaultValue="js"
49+
values={[
50+
{ label: 'Javascript', value: 'js', },
51+
{ label: 'Java', value: 'java', }
52+
]
53+
}>
54+
<TabItem value="js">
55+
56+
```javascript
57+
/**
58+
* Definition for a binary tree node.
59+
* function TreeNode(val, left, right) {
60+
* this.val = (val===undefined ? 0 : val)
61+
* this.left = (left===undefined ? null : left)
62+
* this.right = (right===undefined ? null : right)
63+
* }
64+
**/
65+
66+
const sortedArrayToBST = (nums) => {
67+
68+
let helper = (left, right) => {
69+
if (left > right) return null;
70+
71+
let index = Math.floor((left + right) / 2);
72+
let root = new TreeNode(nums[index]);
73+
root.left = helper(left, index - 1);
74+
root.right = helpter(index + 1, right);
75+
76+
return root;
77+
};
78+
79+
return helper(0, nums.length - 1);
80+
};
81+
```
82+
</TabItem>
83+
<TabItem value="java">
84+
85+
```java
86+
/**
87+
* Definition for a binary tree node.
88+
* public class TreeNode {
89+
* int val;
90+
* TreeNode left;
91+
* TreeNode right;
92+
* TreeNode(int x) { val = x; }
93+
* }
94+
*/
95+
96+
public TreeNode sortedArrayToBST(int[] nums) {
97+
int len = nums.length;
98+
if (len == 0) return null;
99+
if (len == 1) {
100+
TreeNode root = new TreeNode(nums[0]);
101+
return root;
102+
}
103+
int medianIdx = len % 2 == 0 ? len / 2 - 1 : len / 2;
104+
TreeNode root = new TreeNode(nums[medianIdx]);
105+
root.left = sortedArrayToBST(Arrays.copyOfRange(nums, 0, medianIdx));
106+
root.right = sortedArrayToBST(Arrays.copyOfRange(nums, medianIdx + 1, len));
107+
return root;
108+
}
109+
```
110+
</TabItem>
111+
</Tabs>

0 commit comments

Comments
 (0)