binary tree - How to check if all leaves are positioned to the left side of the BinaryTree -
i've been breaking head on tasks lecturer posted prep exams. problem relative easy solve if weren't "own" take on definition of perfect binary tree.
my task this: "check if given binarytree complete (complete = last level needs full and on last level leaves need @ left side of tree. write pointer implementation. below tree complete/perfect tree in definition.
b c d e f
nearly info on internet on perfect or full trees don't tackle specific requirement of " leaves need on left side".
what i've done far write class total number of nodes in given tree , compare expected number based on perfect tree formula ( math.pow(2, depth)-1))
here code:
private int numberofnodes =0; public void printlevelorder(){ linkedblockingqueue<binarynode<e>> stack = new linkedblockingqueue<binarynode<e>>(); binarynode<e> node = root; stack.offer(node); while( !stack.isempty()){ node = stack.poll(); if( node != null){ if( node.getleft() != null){ stack.offer(node.getleft()); }if( node.getright() != null){ stack.offer(node.getright()); } numberofnodes++; system.out.print(node.tostring()+ " "); } else{ return; } } system.out.println(); } public int getmaxdepth(binarynode<e> node){ int l =0, r =0; if( node != null){ if( node.getleft() != null){ l = getmaxdepth(node.getleft()); }if( node.getright() != null){ r = getmaxdepth(node.getright()); } } return 1 + math.max(l,r); } public boolean iscomplete(){ return iscomplete(root); } private boolean iscomplete(binarynode<e> node){ int depth = this.getmaxdepth(node); int expectednodes = (int)(math.pow(2,depth)-1); system.out.println( numberofnodes + " - " + expectednodes); return false; }
what understand question have check complete binary tree doing level order traversal starting root.
during traversal, once find node not full node (a node full node if both left , right children not empty), following nodes must leaf nodes.
if node has empty left child, right child must empty.
Comments
Post a Comment