958. Check Completeness of a Binary Tree - Medium

前往題目

想法

  • BFS檢查左邊node是否為null

思路

  1. BFS
  2. 紀錄上一個node,只要當前node不為null上一個nodenull,就是有空缺處,回傳false

Code

網友解答

class Solution {
    public boolean isCompleteTree(TreeNode root) {
        Queue<TreeNode> q = new LinkedList();

        TreeNode prev = root;

        q.offer(root);

        while (!q.isEmpty()) {
            TreeNode cur = q.poll();

            if (cur != null) {
                // Invalid
                if (prev == null) return false;

                // Add its children
                q.offer(cur.left);
                q.offer(cur.right);
            }
            // Update prev
            prev = cur;
        }
        return true;
    }
}

958. Check Completeness of a Binary Tree - Medium
https://f88083.github.io/2024/11/07/958-Check-Completeness-of-a-Binary-Tree-Medium/
作者
Simon Lai
發布於
2024年11月7日
許可協議