二叉树深度
http://www.lintcode.com/zh-cn/problem/maximum-depth-of-binary-tree/
递归问题最简单的应用,二叉树的深度。
如果没有根节点,则深度为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;
}
}
浙公网安备 33010602011771号