110.平衡二叉树
https://leetcode.cn/problems/balanced-binary-tree/
思路:采取后序遍历思想,先后获得两个左右子树的深度,不断递归检查每个节点的左右子树深度相差是否超过1,如果超过的话说明二叉树不平衡。
#include<cmath>
class Solution {
public:
int getHeight(TreeNode* cur){
if(!cur) return 0;
int leftHeight = getHeight(cur->left);
int rightHeight = getHeight(cur->right);
if(leftHeight == -1 || rightHeight == -1) return -1;
if(abs(leftHeight - rightHeight) > 1) return -1;
return max(leftHeight, rightHeight) + 1;
}
bool isBalanced(TreeNode* root) {
if(getHeight(root) == -1) return false;
return true;
}
};
257. 二叉树的所有路径
https://leetcode.cn/problems/binary-tree-paths/
思路:采用后序遍历思想,寻找每一条路径,但比起单纯的遍历要多使用一个栈来储存已经走过的路径。
递归法:
class Solution {
public:
void btr(TreeNode* cur, vector<string>& result, string path) {
if (!cur) return;
if (!cur->left && !cur->right) {
result.push_back(path);
}
if (cur->left) btr(cur->left, result, path + "->" + to_string(cur->left->val));
if (cur->right) btr(cur->right, result, path + "->" + to_string(cur->right->val));
}
vector<string> binaryTreePaths(TreeNode* root) {
if (!root) return {};
vector<string> result;
btr(root, result, to_string(root->val));
return result;
}
};
迭代法:
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
stack<string> allPaths;
stack<TreeNode*> stk;
if (root) {
stk.push(root);
allPaths.push(to_string(root->val));
}
while (!stk.empty()) {
TreeNode* cur = stk.top();
stk.pop();
string nowPath = allPaths.top();
allPaths.pop();
if (!cur->left && !cur->right) {
result.push_back(nowPath);
}
if (cur->right) {
stk.push(cur->right);
allPaths.push(nowPath + "->" + to_string(cur->right->val));
}
if (cur->left) {
stk.push(cur->left);
allPaths.push(nowPath + "->" + to_string(cur->left->val));
}
}
return result;
}
};
404.左叶子之和
https://leetcode.cn/problems/sum-of-left-leaves/
遍历顺序无所谓,重要的是判断某个节点是不是左叶子节点。
class Solution {
public:
void sum(TreeNode* cur, int& result) {
if (!cur) return;
if (cur->left && !cur->left->left && !cur->left->right) result += cur->left->val;
sum(cur->left, result);
sum(cur->right, result);
}
int sumOfLeftLeaves(TreeNode* root) {
if (!root) return 0;
int result = 0;
sum(root, result);
return result;
}
};