LeetCode-验证二叉树

算法记录

LeetCode 题目:

  二叉树上有 n 个节点,按从 0 到 n - 1 编号,其中节点 i 的两个子节点分别是 leftChild[i] 和 rightChild[i]。

  只有所有节点能够形成且只形成一颗有效的二叉树时,返回 true;否则返回 false。

  如果节点 i 没有左子节点,那么 leftChild[i] 就等于 -1。右子节点也符合该规则。


说明

一、题目

输入: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
输出: true
复制代码

二、分析

  • 只需要对于每个节点作为根节点进行遍历,如果当前遍历过程中能将所有节点都遍历一遍而且不存在重复的节点,name一定就是一棵二叉树了。
  • 但是这样相当于是一个 n ^ 2 的时间复杂度,效果肯定是不佳的,树的一个基本性质就是从根节点出发有且仅有一条路径到达任意子节点,我们在添加关联关系时如果当前节点在之前遍历过而且不是当前已构成树的根节点,就直接 false,如果是根节点的话,那就更换根节点为子节点,继续前进遍历,最后看并查集中有几个根节点。
class Solution {
    public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
        for(int i = 0; i < n; i++) {
            Set<Integer> flag = new HashSet();
            Deque<Integer> queue = new ArrayDeque(); 
            queue.push(i);
            while(!queue.isEmpty()) {
                int temp = queue.poll();
                if(flag.contains(leftChild[temp]) || flag.contains(rightChild[temp])) return false;
                if(leftChild[temp] != -1) {
                    queue.push(leftChild[temp]);
                    flag.add(leftChild[temp]);
                }
                if(rightChild[temp] != -1) {
                    queue.push(rightChild[temp]);
                    flag.add(rightChild[temp]);
                }
            }
            if(flag.size() == n - 1) return true;
        }
        return false;
    }
}
复制代码

总结

二叉树的连通性质。

猜你喜欢

转载自juejin.im/post/7104992473113427981