完全二叉树的定义: 一棵二叉树,除了最后一层之外都是完全填充的,并且最后一层的叶子结点都在左边。
一个直观的想法, 就是观察一棵完全二叉树,来分析它到底有什么特征。
方法1:
- 按层遍历二叉树, 从每层从左向右遍历所有的结点
- 如果当前结点有右孩子, 但没有左孩子, 那么直接返回false
- 如果当前结点并不是左右孩子都有, 那么它之后的所有结点都必须为叶子结点, 否则返回false
- 遍历结束后返回true
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; }