【513. 找树左下角的值】
https://programmercarl.com/0513.找树左下角的值.html
此题使用层序遍历,就是一道层序遍历模板题。
有一点关键的是,左下角的值等于最后一层的第一个节点的值,所以,当便利到每一层的第一个节点的时候,用result记录这个值。
代码如下:
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> que;
if(root!= NULL)que.push(root);
int result = 0;
while(!que.empty()){
int size = que.size();
for(int i = 0; i<size; i++){
TreeNode* node = que.front();
que.pop();
if(i == 0)result = node->val;
if(node->left)que.push(node->left);
if(node->right)que.push(node->right);
}
}
return result;
}
};
在写层序遍历的时候,会出现一个错误。for循环的第二个条件不能写成i<que.size(),因为队列的大小是变化的,需要每次都重新计算队列的大小。
【112. 路径总和】
https://programmercarl.com/0112.路径总和.html#视频讲解
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == NULL)return false;
stack<pair<TreeNode*,int>> st;
st.push(pair<TreeNode*, int>(root, root->val));
while(!st.empty()){
pair<TreeNode*,int> node;
node = st.top();
st.pop();
if(node.first->left==NULL && node.first->right == NULL && node.second == targetSum)return true;
if(node.first->right !=NULL)st.push(pair<TreeNode*, int>(node.first->right, node.second + node.first->right->val));
if(node.first->left !=NULL)st.push(pair<TreeNode*, int>(node.first->left, node.second + node.first->left->val));
}
return false;
}
};
这题的解法是使用栈这种数据结结构来遍历二叉树的节点,顺便记录遍历到的节点的路径之和。
栈里面存放的是两个数据类型<Treenode*,int>
第一个为所遍历到的节点,第二个为路径之和。
终止条件是,当遍历到叶子节点的时候,判断路径之和是否等于所求的节点,等于的话就可以返回true。不等于的话就将节点的左右节点及其路径之和压入栈中(如果左右节点存在)。
【106.从中序与后序遍历序列构造二叉树】
https://programmercarl.com/0106.从中序与后序遍历序列构造二叉树.html#思路
有点难呜呜呜