Domanda di colloquio di Microsoft

Find diameter of binary tree.

Risposta di colloquio

Anonimo

28 lug 2010

int max(int a, int b) { return (a >= b)? a: b; } int maxDepth(struct bTreeNode *root) { if(root == NULL) { return 0; } else { int ld = maxDepth(root->lNode); int rd = maxDepth(root->rNode); if( ld > rd) return ld+1; else return rd+1; } } int diameter(struct bTreeNode *root) { if(root == NULL) { return 0; } else { int ld = diameter(root->lNode); int rd = diameter(root->rNode); int lh = maxDepth(root->lNode); int rh = maxDepth(root->rNode); return max(lh + rh + 1, max(ld, rd)); } }