Skip to content

Commit c268a4a

Browse files
add JS Solution for 0101 0102 0108
1 parent 322a11a commit c268a4a

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed
+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {boolean}
11+
*/
12+
var isSymmetric = function(root) {
13+
if (!root) return true
14+
return checkSymmetric(root.left, root.right)
15+
};
16+
17+
const checkSymmetric = function(leftNode, rightNode) {
18+
if (!leftNode && !rightNode) return true
19+
if (!leftNode || !rightNode) return false
20+
return leftNode.val === rightNode.val && checkSymmetric(leftNode.left, rightNode.right)
21+
&& checkSymmetric(rightNode.left, leftNode.right)
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {number[][]}
11+
*/
12+
var levelOrder = function(root) {
13+
let result = []
14+
if (!root) return result
15+
16+
let queue = []
17+
queue.push(root)
18+
while(queue.length) {
19+
let size = queue.length
20+
let levelItems = []
21+
while(size--) {
22+
let node = queue.shift()
23+
levelItems.push(node.val)
24+
if(node.left) {
25+
queue.push(node.left)
26+
}
27+
if(node.right) {
28+
queue.push(node.right)
29+
}
30+
}
31+
result.push(levelItems)
32+
}
33+
return result
34+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {number[]} nums
10+
* @return {TreeNode}
11+
*/
12+
var sortedArrayToBST = function(nums) {
13+
return nums ? buildTree(nums, 0, nums.length - 1) : null
14+
};
15+
16+
const buildTree = function(nums, left, right) {
17+
if (left > right) return null
18+
let mid = Math.floor((left + right) / 2)
19+
let root = new TreeNode(nums[mid])
20+
root.left = buildTree(nums, left, mid - 1)
21+
root.right = buildTree(nums, mid + 1, right)
22+
return root
23+
}

0 commit comments

Comments
 (0)