[LeetCode 222]Count Complete Tree Nodes

来源:互联网 发布:2017mac mini会更新吗 编辑:程序博客网 时间:2024/06/17 14:06

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.

递归查找左右子树的nodes number, 注意base case.并利用complete tree 性质


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


0 0