在二叉树中找出和为某一值的所有路径

路径的起点为根节点,如

       10                                          
      /   \                                         
     5    12                                       
    /  \                                      
   4   7                输入22,则输出10, 12和10, 5, 7两组数据。

分析:需要找到所有路径,因此需要对树进行遍历。采用前序遍历时,当前的和以及路径可以用来作为左右子树路径的基础。算法用递归实现。

#include <iostream>
using namespace std;

struct BinaryTreeNode // a node in the binary tree
{
    int              m_nValue; // value of node
    BinaryTreeNode  *m_pLeft;  // left child of node
    BinaryTreeNode  *m_pRight; // right child of node
    BinaryTreeNode(int value) {
        m_nValue = value;
        m_pLeft = m_pRight = 0;
    }
};

const int MAX_PATH_LEN = 20;
int pathLength = 0;
int path[MAX_PATH_LEN];

/**
(1) sum > 0;
(2) "root" is a valid binary tree.
*/
void printPathes(int sum, BinaryTreeNode* root) {
    if(pathLength > MAX_PATH_LEN) return;
    path[pathLength] = root->m_nValue;
    pathLength ++;
    sum -= root->m_nValue;
    if(sum == 0) {
        for(int i = 0; i < pathLength; i++) {
            cout << path[i] << " ";
        }
        cout << endl;
    }
    if(root->m_pLeft != NULL) {
        printPathes(sum, root->m_pLeft);
    }
    if(root->m_pRight != NULL) {
        printPathes(sum, root->m_pRight);
    }
    pathLength --;
}

int main() {
    BinaryTreeNode* root = new BinaryTreeNode(10);
    root->m_pLeft = new BinaryTreeNode(5);
    root->m_pLeft->m_pLeft = new BinaryTreeNode(4);
    root->m_pLeft->m_pRight = new BinaryTreeNode(7);
    root->m_pRight = new BinaryTreeNode(12);
    printPathes(22, root);
    return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值