求完全二叉树的节点数 Count Complete Tree Nodes

问题:

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

解决:

【题意】求一个完全二叉树的节点个数。

① 完全二叉树的一个性质是,如果左子树最左边的深度,等于右子树最右边的深度,说明这个二叉树是满的,即最后一层也是满的,则以该节点为根的树其节点一共有2 ^ h - 1个。如果不等于,则是左子树的节点数,加上右子树的节点数,加上自身这一个。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {//297ms
    public static int countNodes(TreeNode root) {
        int lheight = 0;
        int rheight = 0;
        TreeNode pleft = root;
        TreeNode pright = root;
        while (pleft != null){
            lheight ++;
            pleft = pleft.left;
        }
        while (pright != null){
            rheight ++;
            pright = pright.right;
        }
        if (lheight == rheight){
            return (int)Math.pow(2,lheight) - 1;
        }
        return countNodes(root.left) + countNodes(root.right) + 1;
    }
}

② 直接统计

class Solution {//21ms
    public int countNodes(TreeNode root) {
        if(root == null){
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int count = 1;
        while(! queue.isEmpty()){
            TreeNode temp = queue.poll();
            if(temp.val != -1){
                temp.val = -1;//用于标识该节点已经遍历过
                if(temp.left != null){
                    queue.offer(temp.left);
                    count ++;
                }
                if(temp.right != null){
                    queue.offer(temp.right);
                    count ++;
                }
            }
        }
        return count;
    }
}

class Solution {//11ms
    public int countNodes(TreeNode root) {
        if (root == null)
            return 0;
        if (root.val != -1) {
            root.val = -1;
            return 1 + countNodes(root.left) + countNodes(root.right);
        } else {
            return 0;
        }
    }
}

转载于:https://my.oschina.net/liyurong/blog/1591120

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值