Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
often expressed recursively (following the denition of binary tree) depth (or level) of a node:
root has level 1 otherwise 1+ level of parent Denition
height of a tree:
if the tree is empty, its height is 0 otherwise, its height is 1 + max{ height TL, height TR }, where TL and TR designate left and right subtrees
Other ways to dene the height of a tree length of the longest root-leaf path max( level(n) ) over all nodes n in the tree So the height of a singleton tree is 1. (Huh?) Think of the height as the max # of nodes on a root-leaf path, not the number of branches.
Code
public static int height( BinaryTreeInterface t ) // Post: Returns height of subtree. if( t.isEmpty() ) return 0; else { int leftHt = height( t.getLeftSubtree() ); int rightHt = height( t.getRightSubtree() ); return 1 + Math.max( leftHt, rightHt ); } }
A tree of height h having the maximum number of nodes (2h-1) is called a perfect tree.
CS 134 JCBeatty
Page 111
Lets try it out on a few trees ... see if its true see how its true
TA TB TC TD
By the inductive hypothesis, TL has at most 2k-1 -1 nodes and TR has at most 2k-1 -1 nodes. Thus T has at most 1+2(2k-1 -1) = 2k -1 nodes. QED or as required (ie were done).
height < k means height at most k-1 (and since k > 0, k-1 0)
CS 134 JCBeatty
Page 112
TL
TR
CS 134 JCBeatty
Page 113
Strong Induction
To prove P(n) true for all n 0:
Base case: Show that P(0) is true Inductive hypothesis: Assume property P(i) is true for i = 0,1,...,k-1. Inductive step: Show, using the inductive hypothesis, that P(k) is true.
Variations
base case something other than 0 several base cases assume P(0), P(1), ..., P(k) true and use them to prove P(k+1) is true weak (aka natural) induction: assume P(k-1) true and use it alone to prove P(k) is true. (More common for proving formulas regarding sequences of integers, eg 1 + 2 + 3 + ... + n = n(n+1)/2 ).
The form of the inductive proof usually matches the form of the recursion.
CS 134 JCBeatty
Page 114
CS 134 JCBeatty
Page 115