# Base condition Part 2 -11 last left node contains right node only

**URL:** <https://forum.codewithmosh.com/t/base-condition-part-2-11-last-left-node-contains-right-node-only/10989>\
**Category:** Data Structures\
**Created:** [February 28, 2022, 11:39pm UTC](https://forum.codewithmosh.com/t/base-condition-part-2-11-last-left-node-contains-right-node-only/10989 "2022-02-28T23:39:57Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Gary](https://avatars.discourse-cdn.com/v4/letter/g/839c29/32.png) [@Gary](https://forum.codewithmosh.com/u/Gary)\
**Post date:** [February 28, 2022, 11:39pm UTC](https://forum.codewithmosh.com/t/base-condition-part-2-11-last-left-node-contains-right-node-only/10989/1 "2022-02-28T23:39:57Z")

</div>

I am converting examples to Delphi (No good classes in Delphi) so may be slightly different.

All is fine with sample tree where all leaf’s line up even, however adding (3) to tree adds a right node to last left node, correct?

Base condition is looking for a leaf with both child nodes of nil so it fails on last left node(1) so it then calls Height on left child node that does not exist causing A/V  
Have I missed something?

I ended up doing the following :

```auto
if IsLeaf(ANode) then
    Exit(0);

  if HasRightNodeOnly(ANode) then
    result := 1 + HeightOfNode(ANode.Right)
  else if HasLeftNodeOnly(ANode) then
    result := 1 + HeightOfNode(ANode.Left)
  else
    result := 1 + System.Math.Max(HeightOfNode(ANode.Left),
      HeightOfNode(ANode.Right));

```

---

<div class="post-metadata">

**Author:** ![jmrunkle](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/jmrunkle/32/3765_2.png) [@jmrunkle](https://forum.codewithmosh.com/u/jmrunkle)\
**Post date:** [August 6, 2022, 4:24pm UTC](https://forum.codewithmosh.com/t/base-condition-part-2-11-last-left-node-contains-right-node-only/10989/2 "2022-08-06T16:24:10Z")

</div>

Yeah, his code has a bug. I would probably write the Java code like this:

```java
if (root == null) return -1;
return 1 + Math.max(
    height(root.leftChild),
    height(root.rightChild));

```

With that, the leaf nodes will get a height of 0 since the null children will both have a height of -1 and the ones with only one child will add 1 of the height of the child that is not null because the null child will have a height of -1 and the non-null child will be at least a height of 0 (so the non-null child is guaranteed to have the larger height).
