Leetcode 110. 平衡二叉树
链接:110. 平衡二叉树
thought:
-
一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
-
无需多言,DFS递归思路:
-
既然我们要判断所有的二叉树的左右子树的高度差,我们采用后序遍历,从左下逐个开始遍历,记录左右子树高度,并返回max(num1, num2)+1,并逐层封装返回上层,本题基本思路和求最大深度基本相同,多了判断高度差而已。
完整C++代码如下:
class Solution {
public:
bool isBalanced(TreeNode* root) {
bool test = true;
maxDepth(root, test);
return test;
}
int maxDepth(TreeNode* root, bool& test) {
if (!root)
return 0;
int num1 = maxDepth(root->left,test);
int num2 = maxDepth(root->right,test);
if (!test)
return 0;
if (abs(num1 - num2) > 1)
test = false;
return max(num1, num2)+1;
}
};
Leetcode 257. 二叉树的所有路径
thought:
- 求所有路径,立刻想到了先序遍历的优点
完整C++代码如下:
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if(!root)return res;
recursion1(root, res);
return res;
}
void recursion1(TreeNode* root, vector<string>& res) {
static string cur;
if (!root->left && !root->right) {
if (!cur.empty()) {
cur.erase(cur.size() - 2,2);
res.push_back(cur);
}
return;
}
cur += to_string(root->val);
cur += "->";
if (root->left)
recursion1(root->left, res);
if (root->right)
recursion1(root->right, res);
return;
}
};
class Solution {
public:
void getPath(TreeNode* node, string path, vector<string>& ans) {
path += to_string(node->val);
if (node->left == NULL && node->right == NULL) {
ans.push_back(path);
return;
}
if (node->left)
getPath(node->left, path + "->", ans);
if (node->right)
getPath(node->right, path + "->", ans);
return;
}
vector<string> binaryTreePaths(TreeNode* root) {
string path;
vector<string> ans;
if (root == NULL)
return ans;
getPath(root, path, ans);
return ans;
}
};
Leetcode 404. 左叶子之和
链接:404. 左叶子之和
thought:先序遍历
完整C++代码如下:
class Solution {
public:
int res = 0;
int sumOfLeftLeaves(TreeNode* root) {
dfs(root);
return res;
}
void dfs(TreeNode* root) {
if (root == nullptr) {
return;
}
if (root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr) {
res += root->left->val;
}
dfs(root->left);
dfs(root->right);
}
};