首页 > 其他 > 详细

完全二叉树节点个数

时间:2020-07-19 14:40:58      阅读:56      评论:0      收藏:0      [点我收藏+]

技术分享图片

1、没利用完全二叉树性质的递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    Queue<TreeNode> q = new LinkedList<>();
    public int countNodes(TreeNode root) {
    if(root == null) return 0;    
    return countNodes(root.left) + countNodes(root.right) + 1;
        
    }
}

2、因为完全二叉树只有最后一层不是满的。
1.1、左子树不是满二叉树,右子树自然就是满二叉树了

技术分享图片

1.2、左子树是满二叉树,右子树不一定。

技术分享图片

技术分享图片

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int countNodes(TreeNode root) {
        if(root == null){
           return 0;
        } 
        int left = countLevel(root.left);
        int right = countLevel(root.right);
        if(left == right){//左子树是满二叉树
            return countNodes(root.right) + (1<<left);//左子树加上根节点数目刚好是2^left,用位运算快一点
        }else{
            return countNodes(root.left) + (1<<right);//同理
        }
    }
    private int countLevel(TreeNode root){//可以帮助判断是否左子树是满二叉树
        int level = 0;
        while(root != null){
            level++;
            root = root.left;
        }
        return level;
    }
}

完全二叉树节点个数

原文:https://www.cnblogs.com/cstdio1/p/13339047.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!