513.找树左下角的值
这里要注意,我们的结果需要的是最后一行的最左边的值。所以要找到深度最大的叶子结点。
保证优先左边搜索,然后记录深度最大的叶子节点,此时我们要的值就是树的最后一行最左边的值。
class Solution {
public:
int res;
int Maxdept=INT_MIN;
void traversal(TreeNode*root,int depth){
if(root->left==nullptr&&root->right==nullptr){
if(depth>Maxdept){
Maxdept=depth;
res=root->val;
}
}
if(root->left){
depth++;
traversal(root->left,depth);
depth--;
}
if(root->right){
depth++;
traversal(root->right,depth);
depth--;
}
}
int findBottomLeftValue(TreeNode* root) {
traversal(root,0);
return res;
}
};
路径总和
需不需要返回值:
- 如果需要搜索整棵二叉树且不用处理递归返回值,递归函数就不要返回值。
- 如果需要搜索整棵二叉树且需要处理递归返回值,递归函数就需要返回值。
- 如果要搜索其中一条符合条件的路径,那么递归一定需要返回值,因为遇到符合条件的路径了就要及时返回。
class Solution {
public:
bool traversal(TreeNode*root,int count){
if(!root->left&&!root->right&&count==0) return true;
if(!root->left&&!root->right) return false;
if(root->left) {
count-=root->left->val;
if(traversal(root->left,count)) return true;
count+=root->left->val;
}
if(root->right) {
count-=root->right->val;
if(traversal(root->right,count)) return true;
count+=root->right->val;
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root==nullptr) return false;
return traversal(root,targetSum - root->val);
}
};
从中序与后序遍历序列构造二叉树
这题太难了,后面再继续理解。
class Solution {
private:
TreeNode* traversal (vector<int>& inorder, vector<int>& postorder) {
if (postorder.size() == 0) return NULL;
// 后序遍历数组最后一个元素,就是当前的中间节点
int rootValue = postorder[postorder.size() - 1];
TreeNode* root = new TreeNode(rootValue);
// 叶子节点
if (postorder.size() == 1) return root;
// 找到中序遍历的切割点
int delimiterIndex;
for (delimiterIndex = 0; delimiterIndex < inorder.size(); delimiterIndex++) {
if (inorder[delimiterIndex] == rootValue) break;
}
// 切割中序数组
// 左闭右开区间:[0, delimiterIndex)
vector<int> leftInorder(inorder.begin(), inorder.begin() + delimiterIndex);
// [delimiterIndex + 1, end)
vector<int> rightInorder(inorder.begin() + delimiterIndex + 1, inorder.end() );
// postorder 舍弃末尾元素
postorder.resize(postorder.size() - 1);
// 切割后序数组
// 依然左闭右开,注意这里使用了左中序数组大小作为切割点
// [0, leftInorder.size)
vector<int> leftPostorder(postorder.begin(), postorder.begin() + leftInorder.size());
// [leftInorder.size(), end)
vector<int> rightPostorder(postorder.begin() + leftInorder.size(), postorder.end());
root->left = traversal(leftInorder, leftPostorder);
root->right = traversal(rightInorder, rightPostorder);
return root;
}
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if (inorder.size() == 0 || postorder.size() == 0) return NULL;
return traversal(inorder, postorder);
}
};
后面两个题周末再细看,并完成相类似的题。