-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2_4_univalued_binary_tree.js
More file actions
53 lines (51 loc) · 1.21 KB
/
Copy path2_4_univalued_binary_tree.js
File metadata and controls
53 lines (51 loc) · 1.21 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* 965. Univalued Binary Tree
* A binary tree is univalued if every node in the tree has the same value.
* Return true if and only if the given tree is univalued.
*
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* Depth First Search:
* Time complexity recursive implementation O(n)
* Space complexity recursive implementation O(n)
*
* @param {TreeNode} root
* @return {boolean}
*/
function isUnivalTreeDFS(root, val = root.val) {
if (!root) {
return true;
}
return root.val === val && isUnivalTreeDFS(root.left, val) &&
isUnivalTreeDFS(root.right, val);
};
/**
* Iterative version - Breadth First Search:
* Time complexity recursive implementation O(n)
* Space complexity recursive implementation O(n)
*
* @param {TreeNode} root
* @return {boolean}
*/
function isUnivalTreeBFS(root) {
const queue = [];
queue.push(root);
while(queue.length) {
const nodeEl = queue.shift();
if (nodeEl.val !== root.val) {
return false;
}
if (nodeEl.right !== null) {
queue.push(nodeEl.right);
}
if (nodeEl.left !== null) {
queue.push(nodeEl.left);
}
}
return true;
}