[LeetCode]222. Count Complete Tree Nodes

来源:互联网 发布:淘宝商城2016女装新款 编辑:程序博客网 时间:2024/05/29 13:16

https://leetcode.com/problems/count-complete-tree-nodes/

计算完全二叉树中的节点个数




完全二叉树当前结点的左右子树至少有一个是满二叉树

// 完全二叉树树的高度为根节点到最左子树的长度public class Solution {    public int countNodes(TreeNode root) {        // height(root.right) == h - 1表明左子树为满二叉树,再加上root,总共为1 << h,        // height(root.right) == h - 2表明右子树为满二叉树        int h = height(root);        // 位运算全部加括号!!!        return h < 0 ? 0 :             height(root.right) == h - 1 ? (1 << h) + countNodes(root.right) :                 (1 << (h - 1)) + countNodes(root.left);    }    private int height(TreeNode root) {        if (root == null) {            return -1;        }        return 1 + height(root.left);    }}


0 0
原创粉丝点击