【Lintcode】726. Check Full Binary Tree

题目地址:

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值