513.找树左下角的值
https://leetcode.cn/problems/find-bottom-left-tree-value/
思路:使用层序遍历应该是最简单的,每遍历到新的一层就记录这一层第一位的数值。
递归法:
class Solution {
public:
void find(TreeNode* cur, int &result, int &resultDepth, int curDepth) {
if(!cur) return;
if(curDepth > resultDepth) {
result = cur->val;
resultDepth = curDepth;
}
find(cur->left, result, resultDepth, curDepth + 1);
find(cur->right, result, resultDepth, curDepth + 1);
}
int findBottomLeftValue(TreeNode* root) {
int result;
int resultDepth = 0;
find(root, result, resultDepth, 1);
return result;
}
};
迭代法:
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> que;
int result = 0;
if(root) que.push(root);
while(!que.empty()){
int len = que.size();
result = que.front()->val;
while(len--){
if(que.front()->left) que.push(que.front()->left);
if(que.front()->right) que.push(que.front()->right);
que.pop();
}
}
return result;
}
};
112. 路径总和
https://leetcode.cn/problems/path-sum/
这道题目要使用前序遍历,只需要在遍历的时候不断记录当前值总和的大小即可。
class Solution {
public:
void pathSum(TreeNode* cur, int target, int sum, bool& flag) {
if (!cur) return;
if (flag) return; //说明已经找到了一条路径,后面都不需要再遍历了,直接返回就行
if (!cur->left && !cur->right) {
if (target == sum) flag = true;
return;
}
else {
if (cur->left) pathSum(cur->left, target, sum + cur->left->val, flag);
if (cur->right) pathSum(cur->right, target, sum + cur->right->val, flag);
}
}
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
bool flag = false;
pathSum(root, targetSum, root->val, flag);
return flag;
}
};
当然也可以精简一下写法
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
if (!root->left && !root->right) {
if (targetSum == root->val) return true;
return false;
}
bool left = hasPathSum(root->left, targetSum - root->val);
bool right = hasPathSum(root->right, targetSum - root->val);
return left || right; //只要有一个是true说明就已经找到了
}
};
106.从中序与后序遍历序列构造二叉树
https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
本题的重要思路是分割,不断将已经给出的数组,创造根节点,去除数组中根节点后分割成左叶子和右叶子,然后再将他们作为新的遍历数组来创造新的根节点。
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if(inorder.empty() || postorder.empty()) return nullptr;
int midVal = postorder.back();
TreeNode* node = new TreeNode(midVal);
int midIdx = 0;
while(inorder[midIdx] != midVal) midIdx++;
vector<int> leftIno(inorder.begin(), inorder.begin() + midIdx);
vector<int> rightIno(inorder.begin() + midIdx + 1, inorder.end());
vector<int> leftPos(postorder.begin(), postorder.begin() + leftIno.size());
vector<int> rightPos(postorder.begin() + leftIno.size(), postorder.end() - 1);
node->left = buildTree(leftIno, leftPos);
node->right = buildTree(rightIno, rightPos);
return node;
}
};