图论-完全二叉树判定-Check Completeness of a Binary Tree
2020-02-19 13:34:28
问题描述:
问题求解:
判定方式就是采用层序遍历,对于一个完全二叉树来说,访问每个非空节点之前都不能访问过null。
public boolean isCompleteTree(TreeNode root) { if (root == null) return true; Queue<TreeNode> q = new LinkedList<>(); q.add(root); boolean flag = false; while (!q.isEmpty()) { int size = q.size(); for (int k = 0; k < size; k++) { TreeNode curr = q.poll(); if (curr != null) { if (flag) return false; q.add(curr.left); q.add(curr.right); } else flag = true; } } return true; }