树题两则

以下是两道树方面问题的解:

1、由前序遍历序列和中序遍历序列还原构造出一棵二叉树

2、在一棵二叉树中寻找遍历路径上的值之和为指定数字的路径

#include <iostream>
#include <vector>

struct BinaryTreeNode 
{
    BinaryTreeNode* m_left;
    BinaryTreeNode* m_right;
    int var;
};

BinaryTreeNode* ConstructCore(int* prestart,int* preend,int* midstart,int* midend)
{
    BinaryTreeNode* root=new BinaryTreeNode();
    int *rootmid=midstart;
    int leftlen=0;
    root->var=prestart[0];
    root->m_left=root->m_right=NULL;
    
    if (prestart==preend)
    {
        return root;
    }

    while (rootmid<midend && *rootmid!=root->var)
    {
        rootmid++;
    }

    leftlen=rootmid-midstart;

    if (leftlen>0)
    {
        root->m_left=ConstructCore(prestart+1,prestart+leftlen,midstart,rootmid-1);
    }
    if (leftlen<preend-prestart)
    {
        root->m_right=ConstructCore(prestart+leftlen+1,preend,rootmid+1,midend);
    }

    return root;
}

BinaryTreeNode* Construct(int* pre,int* mid,int lenth)
{
    if (pre==NULL || mid==NULL)return NULL;

    return ConstructCore(pre,pre+lenth-1,mid,mid+lenth-1);
}

int SumOfStack(std::vector<int>& stack)
{
    int result=0;
    for (std::vector<int>::iterator it=stack.begin();it!=stack.end();it++)
    {
        result+=*it;
    }
    return result;
}

void FindPathSumEquToNum(BinaryTreeNode* tree,int num,std::vector<int>& stack)
{
    if (tree!=NULL)
    {
        if (SumOfStack(stack) + tree->var == num)
        {
            for (std::vector<int>::iterator it=stack.begin();it!=stack.end();it++)
            {
                printf("%d,",*it);
            }
            printf("%d",tree->var);
            printf("\n");
        }
        else
        {
            stack.push_back(tree->var);
            FindPathSumEquToNum(tree->m_right,num,stack);
            FindPathSumEquToNum(tree->m_left,num,stack);
            stack.pop_back();
        }
    }
}

int main()
{
    int pre[8] = {1,2,4,7,3,5,6,8};
    int mid[8] = {4,7,2,1,5,3,8,6};
    int subtreepre[3] = {3,5,6,8};
    int subtreemid[3] = {5,3,6,8};

    BinaryTreeNode* tree=Construct(pre,mid,8);

    std::vector<int> stack;
    FindPathSumEquToNum(tree,18,stack);


    system("pause");
} 
posted on 2012-10-06 15:44  暗夜的雪  阅读(181)  评论(0编辑  收藏  举报