二元树中找出何为某一值的所有路径 【微软面试100题 第四题】

题目要求:

  输入一个整数和一颗二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。

  打印出和与输入整数相等的所有路径。

  例如输入22,和二叉树如下

      10

     /     \

    5          12

   /   \

    4     7

  则打印出两条路径:10-->12和10-->5-->7.

参考资料:剑指offer第25题

题目分析:

  采用变量expectedSum,currentSum,path。expectedSum表示输入的整数,path为队列,表示之前经过的路径,currentSum表示之前经过路径各结点元素的和。

  如果加上当前结点,expectedSum=currentSum,且当前结点为根结点,则打印路径path;如果不满足则继续递归遍历。

  每次进入一个结点,path队列入队该元素,当递归处理了当前结点的子结点之后,最后需要把当前结点出队列。这样才能保证遍历某条路径时保存到path中的值,不会影响其他路径。

#include <iostream>
#include <queue>

using namespace std;

typedef struct BinaryTreeNode 
{
    BinaryTreeNode *left,*right;
    int data;
}BinaryTreeNode;

void findPath(BinaryTreeNode *pRoot,int expectedSum);
void initTree(BinaryTreeNode **p);
int main(void)
{
    BinaryTreeNode *pRoot = NULL;

    initTree(&pRoot);
    findPath(pRoot,22);

    return 0;
}
void findPath(BinaryTreeNode *pRoot,int expectedSum,deque<int> &path,int currentSum);
void findPath(BinaryTreeNode *pRoot,int expectedSum)
{
    if(pRoot == NULL)
        return ;
    
    deque<int> path;
    int currentSum = 0;
    findPath(pRoot,expectedSum,path,currentSum);
}
//--------------------核心代码----------------------------------
void findPath(BinaryTreeNode *pRoot,int expectedSum,deque<int> &path,int currentSum)
{
    currentSum += pRoot->data;
    path.push_back(pRoot->data);

    bool isLeaf = pRoot->left==NULL && pRoot->right==NULL;
    if(isLeaf && currentSum==expectedSum)
    {
        cout << "A path is found:";
        deque<int>::iterator iter = path.begin();
        for(;iter != path.end();iter++)
        {
            cout << *iter;
            if(iter+1 != path.end())
                cout << "-->";
        }
        cout << endl;
    }

    if(pRoot->left != NULL)
        findPath(pRoot->left,expectedSum,path,currentSum);
    if(pRoot->right != NULL)
        findPath(pRoot->right,expectedSum,path,currentSum);

    path.pop_back();
}
//      10
//     / \
//    5   12
//   / \
//  4   7
void initTree(BinaryTreeNode **p)
{
    *p = new BinaryTreeNode;
    (*p)->data = 10;
 
    BinaryTreeNode *tmpNode = new BinaryTreeNode;
    tmpNode->data = 5;
    (*p)->left = tmpNode;
 
    tmpNode = new BinaryTreeNode;
    tmpNode->data = 12;
    (*p)->right = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
    BinaryTreeNode *currentNode = (*p)->left;
 
    tmpNode = new BinaryTreeNode;
    tmpNode->data = 4;
    currentNode->left = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
    tmpNode = new BinaryTreeNode;
    tmpNode->data = 7;
    currentNode->right = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值