Count Complete Tree Nodes

来源:互联网 发布:北京人口密度数据 编辑:程序博客网 时间:2024/05/23 01:35

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.

这道题有点意思,就是数出树中的顶点数,而这棵树呢,是一棵完全二叉树,根据解释,它每一层都是完整的,除了最后一层,而且它最后一层会先排左边的。

采用二分法去做,首先 从根节点考虑,若最左边的高度和最右边的相等,我们就知道我们可以返回了。若不想等,我们需要确认左子树和右子树哪个节点中包含不完整的节点,换句话说,需要知道,最后一层,从左往右,叶子节点有几个(考虑最后一层不完整的情况)。

那么怎么确定是左子树还是右子树不完整呢,我们需要判断左子树中的右子树的最右深度(left->right),然后呢 如果和左子树的最左子树深度一致,那么我们要递归找右子树了。此时的最后一层的叶子的数目是需要累加的。这里还有一个问题,当右子树的最左子树的深度等于右子树的最右子树的深度时 ,实际上我们已经不再需要遍历了,因为此时可以判定左子树中的叶子节点比右子树中的叶子节点多一。

class Solution {public:    int depthl(TreeNode* node){        int depth=0;        while(node){            node=node->left;            depth++;        }        return depth;    }    int depthr(TreeNode* node){        int depth=0;        while(node){            node=node->right;            depth++;        }        return depth;    }    int countNodes(TreeNode* root) {        TreeNode* node=root;        int maxdepth=depthl(root);        int curlen=maxdepth-1;        int index=0;        if(!root)return 0;        int d1,d2;        TreeNode *left,*right;        d1=depthl(node->left);        d2=depthr(node->right);        if(d1==d2) return pow(2,maxdepth)-1;        while(node){            curlen--;            left=node->left;            right=node->right;            if(!left) return pow(2,maxdepth-1)+index-1;            if(!right) return pow(2,maxdepth-1)+index;            //d1=depthTree(left->left);            d1=depthr(left->right);            if(d1==curlen){                index+=pow(2,curlen);                d1=depthl(right->left);                if(d1==curlen-1){                    return pow(2,maxdepth-1)+index-1;                }                else{                    node=right;                }            }            else{               // index+=pow(2,curlen-1);                node=left;            }                    }        return pow(2,maxdepth-1)+index-1;    }};


0 0
原创粉丝点击