[LeetCode] is Array a Preorder of Some ‌Binary Tree

2764. is Array a Preorder of Some ‌Binary Tree

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool isPreorder(vector<vector<int>>& nodes) {
if(nodes[0][1] != -1) return false;
vector<int> st{nodes[0][0]};
for(int i = 1; i < nodes.size(); i++) {
while(st.size() and st.back() != nodes[i][1]) st.pop_back();
if(st.size() == 0) return false;
st.push_back(nodes[i][0]);
}

return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/08/11/PS/LeetCode/is-array-a-preorder-of-some-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.