Java for LeetCode 222 Count Complete Tree Nodes

时间:2023-03-08 16:06:14
Java for LeetCode 222 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 2h nodes inclusive at the last level h.

解题思路:

计算完全二叉树节点,直接递归会TLE,一个不错的思路是判断是否为满二叉树,然后进行递归,JAVA实现如下:

    public int countNodes(TreeNode root) {
if(root==null)
return 0;
int leftHeight=1,rightHeight=1;
TreeNode temp=root.left;
while(temp!=null){
temp=temp.left;
leftHeight++;
}
temp=root.right;
while(temp!=null){
temp=temp.right;
rightHeight++;
}
if(leftHeight==rightHeight)
return (1<<leftHeight)-1;
return countNodes(root.left)+countNodes(root.right)+1;
}