📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!

  • google app store apple app store
  • ✖

      Question

      A Java method isLeaf(TreeNode node) is intended to check

      if a given node is a leaf in a binary tree. class TreeNode {     int val;     TreeNode left, right;     TreeNode(int x) { val = x; } } public boolean isLeaf(TreeNode node) {     if (node == null) {         return false;     }     return node.left == null || node.right == null; // Potential bug here } If isLeaf is called on a node that has a left child but no right child, what will the method return?
      A true, which is correct for a leaf node. Correct Answer Incorrect Answer
      B false, which is incorrect for a leaf node. Correct Answer Incorrect Answer
      C true, which is incorrect because it's not a leaf. Correct Answer Incorrect Answer
      D false, which is correct because it's not a leaf. Correct Answer Incorrect Answer
      E A NullPointerException. Correct Answer Incorrect Answer

      Solution

      • Dry Run: o Consider a node N that has a left child (N.left is not null) but no right child (N.right is null). This is not a leaf node by definition. o Call isLeaf(N):  node == null is false.  The return statement evaluates N.left == null || N.right == null.  This becomes false || true, which evaluates to true. o So, the method returns true for a node that is not a leaf. • Why Correct Answer (C): true, which is incorrect because it's not a leaf. o The dry run confirms that the method will return true. o The explanation correctly states that this is incorrect because a node with only one child is not a leaf. A correct isLeaf implementation would use && (AND): return node.left == null && node.right == null;.

      Practice Next
      ask-question