【111. Minimum Depth of Binary Tree】
「思路」
利用深度优先算法,预先设定一个比较大的ans值,不断更新ans的最小值,最终找到最短路径。
「代码」
class Solution {
public:
int ans=100000000;
int minDepth(TreeNode* root) {
if(!root)return 0;
DFS(root,1);
return ans;
}
void DFS(TreeNode* root,int a)
{
if(!root) return;
if(!root->left && !root->right)
{
ans=min(ans,a);
return;
}
a++;
DFS(root->left,a);
DFS(root->right,a);
}
};
【104. Maximum Depth of Binary Tree】
「思路」
通过寻找最小路径的算法改编而成。同样利用深度优先算法,预先设定一个ans为0,不断更新ans的最大值,最终找到最长路径。
「代码」
class Solution {
public:
int ans=0;
int maxDepth(TreeNode* root) {
if(!root)return 0;
DFS(root,1);
return ans;
}
void DFS(TreeNode* root,int a)
{
if(!root) return;
if(!root->left && !root->right)
{
ans=max(ans,a);
return;
}
a++;
DFS(root->left,a);
DFS(root->right,a);
}
};
【110. Balanced Binary Tree】
「思路」
借用上述的求最长路径的算法,计算出每条路径的长度。用isBalanced函数做判断,判断左右子树的长度差,如果差大于1则返回false。
「运行结果」
「代码」
class Solution {
public:
int dif=0,ansmax=0;
bool isBalanced(TreeNode* root)
{
if(!root || (!root->left && !root->right)) return true;
DFS_max(root->left,0);
int left=ansmax;
ansmax=0;
cout<<left<<"l"<<endl;
DFS_max(root->right,0);
int right=ansmax;
ansmax=0;
cout<<right<<"r"<<endl;
if(abs(left-right)>1) return false;
else if (!isBalanced(root->left) || !isBalanced(root->right)) return false;
else return true;
}
void DFS_max(TreeNode* root,int a)
{
if(!root)
{
ansmax=max(ansmax,a);
return;
}
a++;
DFS_max(root->left,a);
DFS_max(root->right,a);
}
};