其他分享
首页 > 其他分享> > Leetcode 1361. 验证二叉树 (先根据入度找到根节点,然后遍历二叉树判断是否有环和联通)

Leetcode 1361. 验证二叉树 (先根据入度找到根节点,然后遍历二叉树判断是否有环和联通)

作者:互联网

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;
    }
};

 

标签:rightChild,return,int,入度,leftChild,二叉树,有环,false,root
来源: https://blog.csdn.net/wwxy1995/article/details/120640969