【leetcode】Count Complete Tree Nodes (Java)

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 2hnodes inclusive at the last level h.

题意就是求完全二叉树的节点个数。

解题思路:

这道题比较简单,要利用完全二叉树的性质简化过程:即如果当树的左右节点的高度是相同时,就是一个满二叉树,就可以得到他的节点数为(2^height - 1),其他的情况就可以递归了。

/**
 * 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;
        int rightLevel = countRightLevel(root);
        int leftLevel = countLeftLevel(root);
        
        if(rightLevel == leftLevel)
            return (1 << leftLevel) - 1;
        return countNodes(root.left) + 1 + countNodes(root.right);
    }
    public int countRightLevel(TreeNode root){
        int level = 0;
        TreeNode temp = root;
        while(temp != null){
            level++;
            temp = temp.right;
        }
        return level;
    }
    public int countLeftLevel(TreeNode root){
        int level = 0;
        TreeNode temp = root;
        while(temp != null){
            level++;
            temp = temp.left;
        }
        return level;
    }
}


你可能感兴趣的:(java,LeetCode)