赞
踩
- class Solution {
- public:
- bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
- vector<int> indeg(n);
- for (int i = 0; i < n; i++) {
- if (leftChild[i] != -1) {
- indeg[leftChild[i]]++;
- }
- if (rightChild[i] != -1) {
- indeg[rightChild[i]]++;
- }
- }
- int root = -1;
- for (int i = 0; i < n; i++) {
- if (indeg[i] == 0) {
- root = i;
- break;
- }
- }
- if (root == -1) {
- return false;
- }
-
- unordered_set<int> seen;
- function<bool(int)> dfs = [&](int root){
- if (seen.count(root)) {
- return false;
- }
- seen.insert(root);
- if (leftChild[root] != -1) {
- if(!dfs(leftChild[root])) {
- return false;
- }
- }
- if (rightChild[root] != -1) {
- if(!dfs(rightChild[root])) {
- return false;
- }
- }
- return true;
- };
- return dfs(root) == false ? false : seen.size() == n;
- }
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。