1 110. 平衡二叉树
通过本题可以了解求二叉树深度 和 二叉树高度的差异,求深度适合用前序遍历,而求高度适合用后序遍历。
AC代码:
/**
* 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 query(TreeNode* root) // 求一个树节点的高度 如果这个树根左右节点不平衡了返回-1
{
if(root == nullptr)return 0;
int l = query(root->left);
if(l == -1)return-1;
int r = query(root->right);
if(r == -1)return-1;
int tmp = abs(l-r);
if(tmp > 1)return -1;
else return (max(l,r)+1);
}
bool isBalanced(TreeNode* root) {
// 递归
if(query(root) == -1)return 0;
else return 1;
}
};
2 257. 二叉树的所有路径
也就是在递归之后回溯一下存路径的变量。递归和回溯一般是一起使用的。
AC代码:
/**
* 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:
void qianxu(TreeNode* root,vector<int> path,vector<string>& ans) // 求一个root下面的所有路径放在ans中
{
if(root->left == nullptr && root->right == nullptr)// 边界
{
path.push_back(root->val);
string tmp = "";
for(int i = 0; i < path.size()-1; i++)
{
tmp += to_string(path[i]);
tmp += "->";
}
tmp += to_string(path[path.size() - 1]);
ans.push_back(tmp);
}
if(root->left)
{
path.push_back(root->val);
qianxu(root->left,path,ans);
path.pop_back(); // 回溯
}
if(root->right)
{
path.push_back(root->val);
qianxu(root->right,path,ans);
path.pop_back(); // 回溯
}
}
vector<string> binaryTreePaths(TreeNode* root)
{
vector<string> ans;
vector<int> path;
qianxu(root,path,ans);
return ans;
}
};
3 404. 左叶子之和
我用了一个变量标记当前节点是父节点的左儿子还是右儿子,一遍AC代码:
/**
* 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 haha(TreeNode* root,int l)
{
if(root->left == nullptr && root->right == nullptr)
{
if(l == 1)return root->val;
else return 0;
}
int ans1 = 0;
int ans2 = 0;
if(root->left)ans1 = haha(root->left,1);
if(root->right)ans2 = haha(root->right,2);
return ans1+ans2;
}
int sumOfLeftLeaves(TreeNode* root) {
return haha(root,0); // 特判一下边界
}
};
总结:
1. 不难, 就是递归和回溯的基本复习题。