二叉树的完全性检验

给定一个二叉树的 root ,确定它是否是一个 完全二叉树 。

在一个 完全二叉树 中,除了最后一个关卡外,所有关卡都是完全被填满的,并且最后一个关卡中的所有节点都是尽可能靠左的。它可以包含 1 到 2h 节点之间的最后一级 h 。

示例 1:

输入:root = [1,2,3,4,5,6]
输出:true
解释:最后一层前的每一层都是满的(即,结点值为 {1} 和 {2,3} 的两层),且最后一层中的所有结点({4,5,6})都尽可能地向左。

示例 2:

输入:root = [1,2,3,4,5,null,7]
输出:false
解释:值为 7 的结点没有尽可能靠向左侧。

代码实现:

class Solution {
    int size = 0;
    int maxPosition = 0;
    public boolean isCompleteTree(TreeNode root) {
        dfs(root, 1);
        return size == maxPosition;
    }

    private void dfs(TreeNode root, int position) {
        if (root == null) {
            return;
        }
        size++;
        maxPosition = Math.max(position, maxPosition);
        dfs(root.left, 2 * position);
        dfs(root.right, 2 * position + 1);
    }
}

原题链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

视频讲解:二叉树完全性验证_哔哩哔哩_bilibili

你可能感兴趣的:(算法,数据结构,二叉树,面试,深度优先遍历)