要求
- 求一棵二叉树的最高深度
思路
- 递归地求左右子树的最高深度
实现
1 Definition for a binary tree node. 2 struct TreeNode { 3 int val; 4 TreeNode *left; 5 TreeNode *right; 6 TreeNode(int x) : val(x), left(NULL), right(NULL) {} 7 }; 8 9 class Solution { 10 public: 11 int maxDepth(TreeNode* root) { 12 13 if( root == NULL ) 14 return 0; 15 16 return max( maxDepth( root->left ),maxDepth( root->right )) + 1; 17 } 18 };
相关
- 111 Minimum Depth of Binary Tree