Count Complete Tree Nodes

来源:互联网 发布:java string是什么类型 编辑:程序博客网 时间:2024/06/07 13:40

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.

思路:不能一层一层的算,肯定超时,需要利用tree的数学性质,如果左右两边tree的depth相同,那就是一个full tree,那么个数就是2的n次幂-1个node。相当于计算一个三角形的左右两条边的长度,如果相等,则可以用公式计算出来个数,否则,递归,直到能够相等的,这样可以用公式计算。这样递推公式的最终节点就出来了。注意一点,就是算左边跟右边的时候,传进去的node是root,而不是root.left,和root.right,因为最终是要计算的是从根节点到叶子节点的个数,所以要从根开始。另外,计算的时候,用1的位移就可以达到2的n 次幂的效果。

/** * 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 leftdepth = calleft(root);        int rightdepth = calright(root);        if(leftdepth == rightdepth) {            return (1<<leftdepth)-1;        } else {            return countNodes(root.left) + countNodes(root.right) + 1;        }    }        public int calleft(TreeNode node){        int count = 0;        while(node!=null){            node = node.left;            count++;        }        return count;    }        public int calright(TreeNode node) {        int count = 0;        while(node!=null) {            node = node.right;            count++;        }        return count;    }}


0 0
原创粉丝点击