Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Subscribe to see which companies asked this question以上是題目要求,下面貼出代碼:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
int left,right;
if(root == NULL)
return 0;
left = maxDepth(root->left) + 1;
right = maxDepth(root->right) + 1;
return max(left,right);
}
};
此題考點爲二叉樹的深度優先遍歷,利用遞歸最爲容易理解。根的深度等於max(左子樹和右子樹的深度)+1,同時左子樹的深度又可以用同樣的公式來表示,因此可以用遞歸來求解。葉子節點的深度爲1.