二叉树中和为某一路径的值

思路

递归遍历节点;

每遍历一个节点,计算和,并加入路径‘

if(叶子节点){
    if(和 == 整数){
        输出路径
    }


else {
    递归
}
减去和;
路径push

struct node{
    int value;
    node* left;
    node* right;
}
void findPath(node* root,int target,int sum,vector<int>& path){
    if(root == NULL)return;
    sum += root->value;
    path.push(root->value);
    int isLeaf = !root->left && !root->right;
    if(isLeaf && sum == target){
        for(auto a:path){
            cout << a;
        }
        cout << endl;
    }
    if(root->left)findPath(root->left,target,sum,path);
    if(root->right)findPath(root->right,target,sum,path);

    sum -= root->value;
    path.pop_back();

}

 

相关文章:

猜你喜欢
  • 2021-11-20
相关资源
相似解决方案