513.找树左下角的值
题解
//迭代法
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> que;
int result;
que.push(root);
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode *node = que.front();
que.pop();
if (i == 0 && !node->left && !node->right) {
result = node->val;
}
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return result;
}
//递归法
int result;
int max_depth = INT_MIN;
void traversal__(TreeNode* root, int cur_depth) {
if (!root->left && !root->right) {
if (cur_depth > max_depth) {
max_depth = cur_depth;
result = root->val;
return;
}
}
if (root->left) {
cur_depth++;
traversal__(root->left, cur_depth);
cur_depth--;
}
if (root->right) {
cur_depth++;
traversal__(root->right, cur_depth);
cur_depth--;
}
return;
}
int findBottomLeftValue_(TreeNode* root) {
traversal__(root, 1);
return result;
}
总结
本题如果采用基于层序遍历的迭代法将会很简单。而采用递归法的话会稍微复杂一点,定义全局变量result记录当前最左下角值、定义max_depth记录当前最大深度,我们要寻找的是整颗树中最大深度最左边的结点,因此每个遍历到的叶子结点都是可疑的最左下角结点,如果它的深度比当前记录的深度大,就先认为它是最左下的结点,采用优先遍历左子树的遍历方式可以保证每一层中被记录的一定是最左边的结点。
112.路径总和
题解
vector<int> path;
bool hasPathSum_(TreeNode* root, int targetSum) {
path.push_back(root->val);
if (!root->left && !root->right) {
int sum = 0;
for (int &number: path) {
sum += number;
}
if (sum == targetSum)
return true;
else
return false;
}
if (root->left) {
bool left_result = hasPathSum_(root->left, targetSum);
if (left_result) return true;
else path.pop_back();
}
if (root->right) {
bool right_result = hasPathSum_(root->right, targetSum);
if (right_result) return true;
else path.pop_back();
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if (root == nullptr) return false;
return hasPathSum_(root, targetSum);
}
总结
采用前序遍历,每次都将当前递归传入的结点的值加入path中,当传入的时叶子结点的时候,就表明找到了一条从根节点到叶子结点的路径,开始收集path中的结点值求和后与targetSum比较,若相等没必要再遍历后面结点了,传递true层层返回即可。关键就是还没有找到目标路径的时候,递归返回后,要进行回溯。
106从中序和后序遍历序列构造二叉树
题解
待更新
总结
待更新