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

来源:互联网 发布:微信 for mac 2.0 编辑:程序博客网 时间:2024/06/06 20:29
#include<bits/stdc++.h>using namespace std;void findPath(BinaryTreeNode* pRoot, int exceptedSum){    if(pRoot == NULL){        return;    }    vector<int> path;    int currentSum = 0;    findPath(pRoot, exceptedSum, path, currentSum);}void findPath(BinaryTreeNode* pRoot, int exceptedSum, vector<int>& path, int currentSum){    currentSum += pRoot->m_nvalue;    path.push_back(pRoot->m_nvalue);        //如果是叶节点,且路径上的和等于输入的值    // 打印出这条路径    bool isLeft = pRoot->left == NULL && pRoot->right == NULL    if(currentSum == exceptedSum && isLeft){p        printf(" a path is found:");        vector<int>::iterator iter = path.begin();        while(iter != path.end()){            printf("&d\t", *iter);            iter++;        }        printf("\n");    }        // 若不是叶节点,遍历他的子节点    if(pRoot->left != NULL){        findPath(pRoot->left, expectedSum, path, currentSum);    }    if(pRoor->right != NULL){        findPath(pRoot->right, expectedSum, path,currentSum);    }    // 返回到父节点之前,在路径上删除当前节点    path.pop_back();}

原创粉丝点击