110.平衡二叉树
代码实现
/**
* definition for a binary tree node.
* struct treenode {
* int val;
* treenode *left;
* treenode *right;
* treenode() : val(0), left(nullptr), right(nullptr) {}
* treenode(int x) : val(x), left(nullptr), right(nullptr) {}
* treenode(int x, treenode *left, treenode *right) : val(x), left(left),
* right(right) {}
* };
*/
class solution {
public:
int getgight(treenode* node) {
if (node == nullptr)
return 0;
int left_hight = getgight(node->left);//左
if (left_hight == -1)
return -1;
int right_hight = getgight(node->right);//右
if (right_hight == -1)
return -1;
if (abs(left_hight - right_hight) > 1) {//中
return -1;
}
int result = 1 + max(right_hight, left_hight);
return result;
}
bool isbalanced(treenode* root) {
return getgight(root) == -1 ? false : true;
}
};
心得记录:
1.对于递归的三要素中的函数入口,终止条件右一定的理解了,但是单层的循环条件还是有点模糊,尤其是不同情况下的前中后序的选择。
2. 因为求深度可以从上到下去查 所以需要前序遍历(中左右),而高度只能从下到上去查,所以只能后序遍历(左右中)
257. 二叉树的所有路径 (优先掌握递归)
代码实现
/**
* definition for a binary tree node.
* struct treenode {
* int val;
* treenode *left;
* treenode *right;
* treenode() : val(0), left(nullptr), right(nullptr) {}
* treenode(int x) : val(x), left(nullptr), right(nullptr) {}
* treenode(int x, treenode *left, treenode *right) : val(x), left(left),
* right(right) {}
* };
*/
class solution {
private:
void getpath(treenode* node, vector<int>& path, vector<string>& result) {
// 中
path.push_back(node->val);
if (node->left == nullptr && node->right == nullptr) {
string spath;
for (int i = 0; i < path.size() - 1; i++) {
spath += to_string(path[i]);
spath += "->";
}
spath += to_string(path[path.size() - 1]);
result.push_back(spath);
}
// 左
if (node->left) {
getpath(node->left, path, result);
path.pop_back(); // 回溯,把vector中最后一个删除
}
// 右
if (node->right) {
getpath(node->right, path, result);
path.pop_back(); // 回溯,把vector中最后一个删除
}
}
public:
vector<string> binarytreepaths(treenode* root) {
vector<int> path;
vector<string> result;
if (root == nullptr)
return result;
getpath(root, path, result);
return result;
}
};
心得记录:
1.回溯的使用有了初步的理解,比较灵巧,这里只对最基本的方法进行了理解
404.左叶子之和
代码实现
/**
* definition for a binary tree node.
* struct treenode {
* int val;
* treenode *left;
* treenode *right;
* treenode() : val(0), left(nullptr), right(nullptr) {}
* treenode(int x) : val(x), left(nullptr), right(nullptr) {}
* treenode(int x, treenode *left, treenode *right) : val(x), left(left), right(right) {}
* };
*/
class solution {
public:
int sumofleftleaves(treenode* root) {
if (root == null) return 0;
if (root->left == null && root->right== null) return 0;
int leftvalue = sumofleftleaves(root->left); // 左
if (root->left && !root->left->left && !root->left->right) { // 左子树就是一个左叶子的情况
leftvalue = root->left->val;
}
int rightvalue = sumofleftleaves(root->right); // 右
int sum = leftvalue + rightvalue; // 中
return sum;
}
};
心得记录:
1.有点绕,主要是对判断条件不是很清楚
发表评论