Here's the question you clicked on:

55 members online
  • 0 replying
  • 0 viewing

sahar90

  • 3 years ago

i have a bst and i want to count the number of element of that in java language. and it is so important to run fast; do u think is it ok in all aspect? int countTwoChildren(Node node) { return (node == null ? 0 : countTwoChildren(node.left) + countTwoChildren(node.right) + (node.left!=null && node.right!=null ? 1 : 0)); }

  • This Question is Closed
  1. KonradZuse
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    Yeah the code looks really ugly.... if anything with "speed" it's going to do the same calculations just return funky.... This doesn't work does it? do all your calculations, then return calculation.

  2. sahar90
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    tnx for ur help; do u think is it betther? public int nbNodes(Node root){ int count = 1 // our actual node if(root.left != null){ count += nbNodes(root.left); } if(root.right != null){ count += nbNodes(root.right); } return count; }

  3. KonradZuse
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    kind of hard to read, but yeah returning the variable count is the better choice.

  4. sahar90
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    excuse me; i'll be type it better to be useful for others; tnx for ur help again public int nbNodes(Node root){ int count = 1 if(root.left != null){ count += nbNodes(root.left); } if(root.right != null){ count += nbNodes(root.right); } return count; }

  5. Not the answer you are looking for?
    Search for more explanations.

    • Attachments:

Ask your own question

Sign Up
Find more explanations on OpenStudy
Privacy Policy