データ構造-ツリーのパスの問題_剣指offerとleetcodeの中のプログラミングのテーマの比較
剣指offer
leetcode
タイトル:
Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
The root-to-leaf path1->2represents the number12. The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 =25.
問題を解く思想は上のものと似ていて、違いはあります.
1出力の値、
2判定条件に戻る
3ルートノードを返すときに減算されるのは、ノードを削除するのではなく、値です.
4関数はパスの和(上はvectorが各ノードの値を格納する)を解き始めます.すべての変数として定義する必要があります.そうしないと、関数が終了すると解放され、累積的な結果は得られません.
//
class Solution {
public:
vector > buffer;
vector temp;
vector > FindPath(TreeNode* root,int expectNumber) {
if(root==NULL)
return buffer;
temp.push_back(root->val);
if(expectNumber-root->val==0&&root->left==NULL&&root->right==NULL)// 0
{
buffer.push_back(temp);
}
// ,
if(root->left != nullptr)
FindPath(root->left,expectNumber-root->val);
if(root->right != nullptr)
FindPath(root->right,expectNumber-root->val);
if(temp.size()!=0)
temp.pop_back();// , 。
return buffer;
}
};
//
class Solution {
public:
vector > buffer;
vector temp;
int sum =0;
vector > FindPath(TreeNode* root,int expectNumber) {
if(root==NULL)
return buffer;
sum = sum+root->val;
temp.push_back(root->val);
if(expectNumber== sum &&root->left==NULL&&root->right==NULL)
{
buffer.push_back(temp);
}
// ,
if(root->left != nullptr)
FindPath(root->left,expectNumber);
if(root->right != nullptr)
FindPath(root->right,expectNumber);
if(temp.size()!=0)
sum = sum-root->val;
temp.pop_back();// , 。
return buffer;
}
};
leetcode
タイトル:
Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path1->2represents the number12. The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 =25.
問題を解く思想は上のものと似ていて、違いはあります.
1出力の値、
2判定条件に戻る
3ルートノードを返すときに減算されるのは、ノードを削除するのではなく、値です.
4関数はパスの和(上はvectorが各ノードの値を格納する)を解き始めます.すべての変数として定義する必要があります.そうしないと、関数が終了すると解放され、累積的な結果は得られません.
class Solution {
public:
int sum = 0,pathnum = 0;
int sumNumbers(TreeNode *root) {
if(root == nullptr)
return 0;
pathnum = pathnum*10+root->val;
if(root->left == nullptr && root->right ==nullptr)
sum+=pathnum;
if(root->left !=nullptr)
sumNumbers(root->left);
if(root->right != nullptr)
sumNumbers(root->right);
if(pathnum != 0)
pathnum = (pathnum-root->val)/10;
return sum;
}
};