-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2764-is-array-a-preorder-of-some-binary-tree.js
More file actions
64 lines (55 loc) · 1.66 KB
/
2764-is-array-a-preorder-of-some-binary-tree.js
File metadata and controls
64 lines (55 loc) · 1.66 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
54
55
56
57
58
59
60
61
62
63
64
/**
* 2764. Is Array a Preorder of Some Binary Tree
* https://leetcode.com/problems/is-array-a-preorder-of-some-binary-tree/
* Difficulty: Medium
*
* Given a 0-indexed integer 2D array nodes, your task is to determine if the given array represents
* the preorder traversal of some binary tree.
*
* For each index i, nodes[i] = [id, parentId], where id is the id of the node at the index i and
* parentId is the id of its parent in the tree (if the node has no parent, then parentId == -1).
*
* Return true if the given array represents the preorder traversal of some tree, and false
* otherwise.
*
* Note: the preorder traversal of a tree is a recursive way to traverse a tree in which we first
* visit the current node, then we do the preorder traversal for the left child, and finally, we
* do it for the right child.
*/
/**
* @param {number[][]} nodes
* @return {boolean}
*/
var isPreorder = function(nodes) {
const children = new Map();
let root = null;
for (const [id, parentId] of nodes) {
if (parentId === -1) {
root = id;
} else {
if (!children.has(parentId)) {
children.set(parentId, []);
}
children.get(parentId).push(id);
}
}
const expectedOrder = [];
traverse(root);
for (let i = 0; i < nodes.length; i++) {
if (nodes[i][0] !== expectedOrder[i]) {
return false;
}
}
return true;
function traverse(nodeId) {
if (nodeId === null) return;
expectedOrder.push(nodeId);
const nodeChildren = children.get(nodeId) || [];
if (nodeChildren.length > 0) {
traverse(nodeChildren[0]);
}
if (nodeChildren.length > 1) {
traverse(nodeChildren[1]);
}
}
};