两道题都是思路简单,但是代码两眼一抹黑,多多背多多练
129 Sum Root to Leaf Numbers【默写】
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int dfs(TreeNode* node , int currentSum){
if(!node) return 0;
currentSum = currentSum*10 + node->val;
if(!node->left && !node->right){
return currentSum;
}
int leftSum = dfs(node->left , currentSum);
int rightSum = dfs(node->right , currentSum);
return leftSum + rightSum;
}
int sumNumbers(TreeNode* root) {
//能够将大问题化成一个个小问题且需要记录--》动态规划 但不知道具体结点数(遍历计算)所以选择递归
//深度优先搜索
return dfs(root,0);
}
};
236 Lowest Common Ancestor of a Binary Tree【默写】
注意要在递归过程中对引用的vector做改变加&!!!
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool findPath(TreeNode* node , vector<TreeNode*>& path, TreeNode* target){
if(!node)return false;
path.push_back(node);
if(node == target){
return true;
}
if((node->left && findPath(node->left, path , target))||
(node->right && findPath(node->right, path , target))){
return true;
}
//如果该路径不包含目标结点,则移除最后一个结点
path.pop_back();
return false;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
//找LCA最近祖先---》先序×深度搜索√
//node.val 是不重复的
//分别找到两条路径再进行比较
vector<TreeNode*> pathp , pathq;
if(!findPath(root,pathp ,p) || !findPath(root ,pathq ,q)){
return nullptr;//其中一条路不存在
}
int i = 0;
for( ; i < pathp.size() && i < pathq.size() ; i++){
if(pathp[i] != pathq[i]) break;
}
return pathp[i-1];
}
};