题目地址:
https://www.lintcode.com/problem/check-full-binary-tree/description
给定一棵二叉树,判断其是否为full binary tree。其定义为,每个节点的孩子数要么是 0 0 0要么是 2 2 2。
可以用分治法。先判断root本身是否满足那个条件,如果不满足则直接返回false,接着再分别判断左右子树是否满足。代码如下:
public class Solution {
/**
* @param root: the given tree
* @return: Whether it is a full tree
*/
public boolean isFullTree(TreeNode root) {
// write your code here
// 如果是空树则返回true
if (root == null) {
return true;
}
// 如果树是平凡的,则返回true;如果只有一棵子树则返回false;否则分治判断左右子树
if (root.left == null && root.right == null) {
return true;
} else if (root.left == null || root.right == null) {
return false;
} else {
return isFullTree(root.left) && isFullTree(root.right);
}
}
}
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) {
val = x;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)。