完全二叉树的定义: 一棵二叉树,除了最后一层之外都是完全填充的,并且最后一层的叶子结点都在左边。
方法1:
public class TreeNode { public TreeNode(int v) { Val = v; } public int Val { get; private set;} public TreeNode Left { get; set; } public TreeNode Right { get; set; } } public bool IsCompleteBinaryTree(TreeNode root) { if(root == null) return true; Queue<TreeNode> queue = new Queue<TreeNode>(); queue.Enqueue(root); bool shouldBeLeaf = false; while(queue.Count > 0) { var node = queue.Dequeue(); if(shouldBeLeaf && (node.Left != null || node.Right != null)) { return false; } if(node.Left == null && node.Right != null) { return false; } if(node.Left != null) { queue.Enqueue(node.Left); } if(node.Right != null) { queue.Enqueue(node.Right); } else { shouldBeLeaf = true; } } return true; }
原文:http://www.cnblogs.com/johnson-lu/p/5164523.html