解法一:遞迴
1 int maxDepth(TreeNode* root) 2 { 3 if (root == NULL) 4 return 0; 5 6 int max_left_Depth = maxDepth(root->left); 7 int max_right_Depth = maxDepth(root->right); 8 return max(max_left_Depth, max_right_Depth) + 1; 9 }
解法二:BFS
1 int maxDepth(TreeNode* root) 2 { 3 if (root == NULL) 4 return 0; 5 6 queue<TreeNode*> node_queue; 7 node_queue.push(root); 8 9 int count = 0; 10 while (!node_queue.empty()) { 11 count++; 12 int len = node_queue.size(); 13 for (int i = 0; i < len; ++i) { 14 TreeNode *node = node_queue.front(); 15 node_queue.pop(); 16 17 if (node->left) 18 node_queue.push(node->left); 19 if (node->right) 20 node_queue.push(node->right); 21 } 22 } 23 return count; 24 }