104原題地址:https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
111原題地址:https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
題目描述
把這兩題放一起因為是因為這兩題要求差不多,104題要求一棵二叉樹的最大深度,111題要求一棵二叉樹的最小深度。
104題思路
用DFS遍歷,每個DFS返回自己的兩個子節點的路徑長度中較大的那一個。
代碼如下:
/**
* 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 DFS(TreeNode* root,int current_depth){
if(root==NULL){
return current_depth;
}
current_depth+=1;
int depth1 = DFS(root->left,current_depth);
int depth2 = DFS(root->right,current_depth);
return (depth1>depth2?depth1:depth2);
}
int maxDepth(TreeNode* root) {
if(root==NULL){
return 0;
}
int depth = 0;
return DFS(root,depth);
}
};
111題思路
111題求最小深度要比104麻煩一些,因為在DFS里不能直接返回兩個子節點的路徑長度里較小的那個,否則遇到一些節點的某個子節點為空就會直接返回到這個節點為止的路徑長度。如下圖
失敗樣例.png
如果直接返回子節點路徑長度里較小的那個,這個樣例里的返回值為2而不是3。所以這一題要根據子節點的具體情況來決定進行什么樣的操作。
代碼
/**
* 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 DFS(TreeNode* root,int current_depth){
current_depth+=1;
if(root->left!=NULL && root->right!=NULL){
int left =DFS(root->left,current_depth);
int right = DFS(root->right,current_depth);
return (left>right?right:left);
}
if(root->left == NULL && root->right ==NULL){
return current_depth;
}
if(root->left!=NULL){
return DFS(root->left,current_depth);
}
if(root->right !=NULL ){
return DFS(root->right,current_depth);
}
}
int minDepth(TreeNode* root) {
if(root==NULL){
return 0;
}
int depth = 0;
return DFS(root,depth);
}
};