222. Count Complete Tree Nodes

来源:互联网 发布:ipad如何升级淘宝店铺 编辑:程序博客网 时间:2024/06/06 00:09

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; }
* }
*/
class Solution {
public static int countNodes(TreeNode root){
if(root == null){
return 0;
}

    int hl = getLeft(root)+1;    int hr = getRight(root)+1;    if(hl == hr){        int num = (2<<(hl-1))-1;        return num;    }else{        return countNodes(root.left)+countNodes(root.right)+1;    }}public static int getRight(TreeNode root) {    int cou = 0;    TreeNode ptr = root;    while(ptr.right != null){        cou++;        ptr = ptr.right;    }    return cou;}public static int getLeft(TreeNode root) {    int cou = 0;    TreeNode ptr = root;    while(ptr.left != null){        cou++;        ptr = ptr.left;    }    return cou;}

}

原创粉丝点击