1. 程式人生 > >Leetcode | 104. 二叉樹的最大深度

Leetcode | 104. 二叉樹的最大深度

init str left int def lee leet spa return

題目

測試代碼

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxDepth(TreeNode* root) 
13 { 14 if(!root) 15 return 0; 16 int count = 0; 17 int nums = 0; 18 dfs(root, count, nums); 19 return nums; 20 } 21 22 void dfs(TreeNode *root, int count, int &nums) 23 { 24 ++count; 25 if
(count > nums) 26 nums = count; 27 if(!root->left && !root->right) 28 return; 29 if(root->left) 30 dfs(root->left, count, nums); 31 if(root->right) 32 dfs(root->right, count, nums);
33 } 34 };

測試代碼

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxDepth(TreeNode* root) {
13         if (!root) return 0;
14         return 1 + max(maxDepth(root->left), maxDepth(root->right));
15     }
16 };

Leetcode | 104. 二叉樹的最大深度