Today in Leetcode, meet a topic, which calculates the number of nodes of a complete binary tree. Share your experience here.
First, you need to fully master what is a fully binary tree?
I think there is one thing to note about the concept of a complete binary tree. Complete binary tree: Except for the last layer, the number of nodes on each layer reaches the maximum, and on the last layer there are only a few junctions on the right. The last layer of the knot must be left-leaning. The main idea is to think of a node as "root node", then, and then determine whether it is full two fork tree, because full two fork tree is calculated very simple 2k-1 (k=1,2,3 "), that is, for a full two fork tree only need to calculate its depth, That is, using a full two fork tree to simplify the calculation of the complete binary tree. Of course, there is also a very simple way, is to traverse each node, at the same time as the traversal of the count, obviously this is not a good way.
First, the implementation of Python is posted.
1 classTreeNode:2 def __init__(self, x):3Self.val =x4Self.left =None5Self.right =None6 7 classSolution:8 #@param {TreeNode} root9 #@return {integer}Ten def __init__(self): OneSelf.count =0 A - defCountnodes (self, root): - if notRoot: the return0 -Ldepth =self.getdepth (root.left) -Rdepth =self.getdepth (root.right) - ifLdepth = =rdepth: + return(1 << ldepth) +self.countnodes (root.right) - Else: + return(1 << rdepth) +self.countnodes (root.left) A at defgetdepth (self, root): -Depth=0 -node =Root - whilenode: -node =Node.left -Depth + = 1 in - returnDepth
Next, the C language implements this algorithm, and the idea is exactly the same as above.
1 structTreeNode {2 intVal;3 structTreeNode *Left ;4 structTreeNode *Right ;5 };6 7 intCountnodes (structtreenode*root) {8 intldepth, rdepth;9 Ten if(Root = =NULL) { One return 0; A } - -Ldepth = Getdepth (root->Left ); theRdepth = Getdepth (root->Right ); - - if(Ldepth = =rdepth) { - return(1<<ldepth) + countnodes (root->Right ); + } - Else{ + return(1<<rdepth) + countnodes (root->Left ); A } at } - - intGetdepth (structtreenode*node) { - intdepth =0; - - while(node) { innode = node->Left ; -depth++; to } + - returndepth; the}
For, the above code must be aware that for (1<<ldepth) and (1<<rdepth) must pay attention to the parentheses, because "+" than "<<" priority.
Calculates all node points for a complete binary tree