/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/classSolution{Deque<TreeNode> queue =newArrayDeque<>();publicbooleanisCompleteTree(TreeNode root){queue.offer(root);returnbfs(1,1);}publicbooleanbfs(int nodeNums,int except){if(queue.size()==0){returntrue;}int counts =0;boolean flag =false;for(int i =0; i < nodeNums; i++){TreeNode tempNode = queue.pop();if(tempNode.left !=null){if(flag){returnfalse;}queue.offer(tempNode.left);counts++;}else{flag =true;}if(tempNode.right !=null){if(flag){returnfalse;}queue.offer(tempNode.right);counts++;}else{flag =true;}}if(nodeNums != except &&!queue.isEmpty()){returnfalse;}returnbfs(counts,2* except);}}
BFS
注意:要使用能存储 null 值的集合类(比如 ArrayDeque 就不行)
核心思路:当前节点为空时,如果后面(包括右边、下面)有节点则不是完全二叉树。
classSolution{// 完全二叉树判断:当前节点为空时,后面(包括右边、下面)不能有节点publicbooleanisCompleteTree(TreeNode root){LinkedList<TreeNode> queue =newLinkedList<>();queue.offer(root);for(TreeNode cur = queue.poll(); cur !=null; cur = queue.poll()){queue.offer(cur.left);queue.offer(cur.right);}// 如果之后还有非空元素,说明不是完全二叉树while(!queue.isEmpty()){if(queue.poll()!=null){returnfalse;}}returntrue;}}
二刷
classSolution{publicbooleanisCompleteTree(TreeNode root){// jojo的奇妙做法。。不知道怎么想的,反正 A 了,问题不大!List<TreeNode> list =newLinkedList<>();Queue<TreeNode> queue =newArrayDeque<>();queue.offer(root);list.add(root);while(!queue.isEmpty()){TreeNode temp = queue.poll();list.add(temp.left);list.add(temp.right);if(temp.left !=null){queue.offer(temp.left);}if(temp.right !=null){queue.offer(temp.right);}}boolean flag =false;for(TreeNode temp : list){if(temp ==null){flag =true;}elseif(flag){returnfalse;}}returntrue;}}
简单写法,八行代码光速解决~
classSolution{publicbooleanisCompleteTree(TreeNode root){LinkedList<TreeNode> queue =newLinkedList<>();for(TreeNode cur = root; cur !=null; cur = queue.poll()){queue.offer(cur.left);queue.offer(cur.right);}while(!queue.isEmpty()){if(queue.poll()!=null){returnfalse;}}returntrue;}}