您的位置:首页 > 职场人生

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

2014-11-04 11:43 573 查看
题目要求:

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

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

  例如输入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;
 
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐