222. Count Complete Tree Nodes

来源:互联网 发布:人民银行金融数据 编辑:程序博客网 时间:2024/06/07 20:00

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.

利用完全二叉树的性质。首先求整棵树的高度。然后分两种情况考虑:
第一种,右子树的高度和整棵树的高度相等,也就是右子树到达树的最底部。此时,左子树一定是满的,所以无需遍历左子树,可用公式直接计算出左子树的节点个数。然后递归求解右子树的节点个数。
这里写图片描述

第二种,右子树的高度小于整棵树的高度,即右子树的高度等于整棵树的高度减一。此时,右子树一定是满的,无需遍历右子树,直接用公式计算出右子树的个数。然后递归求解左子树的节点个数。
这里写图片描述

程序如下:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int countNodes(TreeNode root) {        if(root == null) {            return 0;        }        return bs(root, 1, getHeight(root));    }    // 递归求解树的高度    public int getHeight(TreeNode root) {        if(root == null) {            return 0;        }        int height = 1;        while(root.left != null) {            root = root.left;            height++;        }        return height;    }    // l代表当前为第几层    // h表示整棵树的高度        public int bs(TreeNode root, int l, int h) {        if(root == null) {            return 0;        }        int level = getHeight(root.right) + l;        if(level == h) { // 第一种情况            return  (1 << (h - l)) + bs(root.right, l + 1, h);        }else { // 第二种情况            return (1 << (h - 1- l)) + bs(root.left, l + 1, h);        }    }}
原创粉丝点击