top | item 19959153

(no title)

bergerjac | 6 years ago

The best way I've found is to imagine a physical tree, and perhaps go outside and stand in front of a big one...

Notice there are 2 types of parts:

  - A leaf, which is the end (has no children)
  - A branch, which may have leaves or more branches (has children)... and because a branch can have more branches, this is recursion, so we abstract to a 3rd type of part:
  - A node, which could be a branch or a leaf...
Imagine if you were blind and had to feel your hand up the stem, and when you reach a node, you'd move your hand up the node to check 'is this a leaf, or a branch' If it's a leaf, you mark it; but if it's a branch, you move your hand along the branch and do the same check for the next nodes 'is this a leaf, or a branch'...

  function int getNumLeaves(Node node):
    foreach childNode in node:
      if childNode.IsLeaf(): leafCount++
      else: return getNumLeaves(childNode) // NOT a leaf -> check this branch's children

  print getNumLeaves(tree.stem); // (start with the outermost 'node')
The pseudocode above could have errors, but it's simple enough to get started for understanding;)

discuss

order

No comments yet.