遞歸問題最簡單的應用,二叉樹的深度。
如果沒有根節點,則深度爲0; if (root==NULL) return 0; 這也是遞歸調用的出口;
然後遞歸調用,先遍歷左子,然後遍歷右子樹。
最後比較左右子樹的深度大小,返回較大值...
int maxDepth(TreeNode *root) {
// write your code here
if (root==NULL) return 0;
else { int l= maxDepth(root->left)+1;
int r= maxDepth(root->right)+1;
if (l>=r) return l;
else return r;
}
}