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

题目描述:输入一颗二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径

二叉树结点定义:

//二叉树定义
struct BinTreeNode{
  int m_value;
  BinTreeNode *left;
  BinTreeNode *right;
    //创建根节点,值为e
  BinTreeNode* createRoot(int e);
  //将e作为当前结点的左孩子值插入
  void insertAsLC(int e);
  //将e作为当前结点的右孩子值插入
  void insertAsRC(int e);
};

解题思路:

  1. 首先要明白,路径指的是以根节点为起点至叶节点
  2. 由于以根为起始点,所以我们需要用到前序遍历
  3. 把经过的路径上的节点保存下来。每访问到一个节点的时候,我们都把当前的节点添加到路径中去。
  4. 到叶节点时计算值。
  5. 再遍历其他节点,遍历下一节点前要回溯
  6. 回溯时删除当前结点并减去当前节点值。

测试用例:

int main(){
    //创建一颗二叉树
    BinTreeNode *tree = new BinTreeNode;
    tree->m_value = 8;
    BinTreeNode *tree2 = new BinTreeNode;
    tree2 = NULL;
    tree->insertAsLC(6); //左孩子为6
    tree->insertAsRC(10);

    tree->left->insertAsLC(5);
    tree->left->insertAsRC(7);

    tree->right->insertAsLC(1);
    tree->right->insertAsRC(11);

    //寻找是否存在值为19的路径
    FindPath(tree, 19); //Output: A path is found: 8 6 5和A path is found: 8 10 1

    return 0;
}

函数实现:

//辅助函数,核心过程
void FindPath(BinTreeNode *pRoot, int expectedSum, std::vector<int> &path, int currentSum){
    //根节点值
    currentSum += pRoot->m_value;
    //根节点入向量
    path.push_back(pRoot->m_value);
    //递归基,如果是叶节点并且路径上的节点的和等于输入的值
    bool isLeaf = pRoot->left == NULL && pRoot->right == NULL;
    if(currentSum == expectedSum && isLeaf){
        //那么打印路径
        std::cout << "A path is found: ";
        std::vector<int>::iterator iter = path.begin();
        for(; iter != path.end(); ++iter)
            std::cout << *iter << " ";
        std::cout << std::endl;
    }
    //如果不是叶节点,则遍历它的子节点
    if(pRoot->left != NULL)
        FindPath(pRoot->left, expectedSum, path, currentSum);
    if(pRoot->right != NULL)
        FindPath(pRoot->right, expectedSum, path, currentSum);
    //在返回父节点之前,在路径上删除当前结点
    path.pop_back();
}
//主函数
void FindPath(BinTreeNode *pRoot, int expectedSum){
    if(pRoot == NULL)
        return;
    //使用向量保存路径
    std::vector<int> path;
    //当前和
    int currentSum = 0;
    //核心函数
    FindPath(pRoot, expectedSum, path, currentSum);
}

其他函数:

//其他函数实现
//创建根节点,值为e
BinTreeNode* BinTreeNode::createRoot(int e){
     BinTreeNode *root = new BinTreeNode;
     root->m_value = e;
     return root;
 }

//作为节点的左孩子插入元素e
void BinTreeNode::insertAsLC(int e){
    BinTreeNode *Left = new BinTreeNode;
    Left->m_value = e;
    this->left = Left;
}

//作为节点的右孩子插入元素e
void BinTreeNode::insertAsRC(int e){
    BinTreeNode *Right = new BinTreeNode;
    Right->m_value = e;
    this->right = Right;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值