首页 > 其他 > 详细

Check whether a given Binary Tree is Complete or not 解答

时间:2015-10-25 01:00:35      阅读:204      评论:0      收藏:0      [点我收藏+]

Question

complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

Solution 1 -- BFS

Using BFS and a flag.

 1 public class Solution {
 2     public boolean checkCompleteBinaryTree(TreeNode root) {
 3         // BFS
 4         // flag whether means previous node has both children
 5         boolean flag = true;
 6         List<TreeNode> current = new ArrayList<TreeNode>();
 7         List<TreeNode> next;
 8         current.add(root);
 9 
10         while (current.size() > 0) {
11             next = new ArrayList<TreeNode>();
12             for (TreeNode node : current) {
13                 if (!flag && (node.left != null || node.right != null))
14                     return false;
15                 if (node.left == null && node.right != null)
16                     return false;
17                 if (node.left != null) {
18                     next.add(node.left);
19                     if (node.right != null) {
20                         next.add(node.right)
21                         flag = true;
22                     } else {
23                         flag = false;
24                     }
25                 }
26             }
27             current = next;
28         }
29 
30         return true;
31     }
32 }

 

Solution 2 -- Recursive

Using recursion

 

Check whether a given Binary Tree is Complete or not 解答

原文:http://www.cnblogs.com/ireneyanglan/p/4908103.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!