Middle-题目95:222. Count Complete Tree Nodes

来源:互联网 发布:中国人工智能协会 编辑:程序博客网 时间:2024/06/05 19:18

题目原文:
Given a complete binary tree, count the number of nodes.
题目大意:
给出一个完全二叉树,求节点数。
题目分析:
如果直接递归数节点,会超时。所以要考虑完全二叉树的性质:左右子树都是完全二叉树。所以分别求左右子树高度,如果相等则为满二叉树,如果不等则递归统计左右子树即可。
源码:(language:java)

public class Solution {    public int countNodes(TreeNode root) {        if(root == null)            return 0;        else {            int leftHeight = 0,rightHeight = 0;            TreeNode left = root,right = root;            while(left!=null) {                left=left.left;                leftHeight++;            }            while (right!=null) {                right = right.right;                rightHeight++;            }            if(leftHeight == rightHeight) // full binary tree                //return (int) (Math.pow(2, leftHeight)-1);                 return (2<<(leftHeight-1)) - 1;            else                return 1+countNodes(root.left)+countNodes(root.right);        }    }}

成绩:
112ms,beats 59.26%,众数116ms,3.89%
cmershen的碎碎念:
其实完全二叉树还有一个性质,就是左右子树至少有一个是满二叉树。这样的话只需要一个递归即可。

0 0
原创粉丝点击