6.6最小深度二叉树
class Solution {//后序遍历
public:
int getMin(TreeNode* bt){
if(!bt) return 0;
int m = getMin(bt->left);
int n = getMin(bt->right);
if(bt->left&&!bt->right)//右子树不存在则不一定是最小高度
return m+1;
if(bt->right&&!bt->left)
return n+1;
int result = min(n,m)+1;//左右子树都存在则返回相对小的树高
return result;
}
int minDepth(TreeNode* root) {
return getMin(root);
}
};
6.7完全二叉树的结点
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
return 1+countNodes(root->left)+countNodes(root->right);
}
};
6.8平衡二叉树
class Solution {
public:
int getHigh(TreeNode* node){
if(!node) return 0;
int leftheight = getHigh(node->left);
if(leftheight == -1) return -1;
int rightheight = getHigh(node->right);
if(rightheight == -1) return -1;
return abs(leftheight-rightheight)>1?-1:1+max(leftheight,rightheight);//左右子树绝对值之差超过1则返回-1,否则返回当前树高
}
bool isBalanced(TreeNode* root) {
int result = getHigh(root);
return result==-1?false:true;
}
};
6.9二叉树的所有路径
class Solution {
private:
void getPath(TreeNode* bt,vector<int>& path,vector<string>& result){
path.push_back(bt->val);
if(!bt->left&&!bt->right){//访问到叶子结点才出手
string spath;
for(int i = 0;i<path.size()-1;i++){
spath += to_string(path[i]);//path路径的值除了叶子结点赋值给spath(强制转换)
spath += "->";
}
spath += to_string(path[(path.size()-1)]);//叶子结点值入路径
result.push_back(spath);
return;
}
if(bt->left){
getPath(bt->left,path,result);
path.pop_back();//只有向上回溯才会pop
}
if(bt->right){
getPath(bt->right,path,result);
path.pop_back();
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if(!root) return result;
getPath(root,path,result);
return result;
}
};