剑指offer(面试题34):二叉树中和为某一值的路径

/*
* 给定一个整数sum,找出二叉树路径上的结点值的总和等于sum的所有路径 
* 方法:先序遍历 + 递归 + 栈 
*/

#include<iostream>
#include<vector>
using namespace std;

struct BinaryTreeNode {
    int value;
    BinaryTreeNode* left;
    BinaryTreeNode* right;
    BinaryTreeNode(int value):left(NULL),right(NULL){
        this->value = value;
    }
};

BinaryTreeNode* createBinaryTree(int value) {
    if(value <= 0)
        return NULL;

    BinaryTreeNode* pNode = new BinaryTreeNode(value);
    pNode->left = createBinaryTree(--value);
    pNode->right = createBinaryTree(value);
    return pNode;
}

void findPathRecursive(BinaryTreeNode* pNode, vector<int>& path, 
                        int currentSum, int sum) {

    currentSum += pNode->value;
    path.push_back(pNode->value);

    bool isLeaf = pNode->left == NULL && pNode->right == NULL;
    if(currentSum == sum && isLeaf) {
        vector<int>::iterator iter = path.begin();
        for(;iter != path.end(); iter++)
            cout << *iter << "->";
        cout << "end" << endl;
    }

    // 递归遍历和计算左、右子树的路径  
    if(pNode->left != NULL)
        findPathRecursive(pNode->left, path, currentSum, sum);
    if(pNode->right != NULL)
        findPathRecursive(pNode->right, path, currentSum, sum);
    // 返回父节点前删除当前结点 
    path.pop_back();
}

void findPath(BinaryTreeNode* pNode, int sum) {
    if(pNode == NULL) 
        return;

    vector<int> path;
    int currentSum = 0;
    findPathRecursive(pNode, path, currentSum, sum);
}

void inOrder(BinaryTreeNode* root) {
    if(root == NULL)
        return;
    if(root->left)
        inOrder(root->left); 

    cout << root->value << " ";

    if(root->right) 
        inOrder(root->right);
}

int main() {
    BinaryTreeNode* root = createBinaryTree(4);
    cout << "中序遍历" << endl;
    inOrder(root); 
    cout <<endl<<endl;
    cout << "sum = 10" <<endl;
    findPath(root, 10);
    cout << "sum = 7" <<endl;
    findPath(root, 7);
    cout << "sum = 6" <<endl;
//  findPath(root, 6);
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值