• 数据结构与算法面试题80道(4)


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

    题目:输入一个整数和一棵二元树。

    从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。

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

    例如 输入整数22和如下二元树

     10 

     /   

     5 12  

     /     

    4     7

    则打印出两条路径:10, 1210, 5, 7

    二元树节点的数据结构定义为:

    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

    };

    思路:设题中的值为sum,遍历二叉树,每走过一个结点,用(sum-那个结点的值),将那个结点的值放入path[]。

    如果遍历到叶子结点,判断sum是否为0,如果是,打印path[]。否则回溯。

    注意:回溯时,sum要加上最后一个结点的值,并且path[]要删掉最后一个结点。

    #include<iostream>
    #include<cstdio>
    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
    };
    
    //添加结点,不解释了
    void addBinaryTreeNode(BinaryTreeNode *&btn,int value){ if(btn==NULL){ BinaryTreeNode *CurrentBinaryTree=new BinaryTreeNode(); CurrentBinaryTree->m_nValue=value; CurrentBinaryTree->m_pLeft=NULL; CurrentBinaryTree->m_pRight=NULL; btn=CurrentBinaryTree; }else if(btn->m_nValue>value) addBinaryTreeNode(btn->m_pLeft,value); else if(btn->m_nValue<value) addBinaryTreeNode(btn->m_pRight,value); else cout<<"node repeated,default ignore"<<endl; }//print path void printPath(int path[],int top){ for(int i=0;i<top;i++) printf("%d ",path[i]); printf(" "); } //查找和为SUM的路径,path数据存放路径的值,top代表每个可行的路径中的元素个数
    //思路如上
    void findPath(BinaryTreeNode *btn,int sum,int top,int path[]){ path[top++] =btn->m_nValue; sum-=btn->m_nValue;//将当前值加入path[],sum减去当前值。
    //如果结点为叶子结点,打印路径
    if(btn->m_pLeft==NULL&&btn->m_pRight==NULL){ if(sum==0) printPath(path,top); }else{//否则向它的子节点遍历。 if(btn->m_pLeft!=NULL) findPath(btn->m_pLeft,sum,top,path); if(btn->m_pRight!=NULL) findPath(btn->m_pRight,sum,top,path); } top--; sum+=btn->m_nValue;//回溯 } int main(){ BinaryTreeNode *T=NULL; addBinaryTreeNode(T,10); addBinaryTreeNode(T,12); addBinaryTreeNode(T,5); addBinaryTreeNode(T,7); addBinaryTreeNode(T,4); int path[10]; int sum=22,top=0; findPath(T,sum,top,path); return 0; }
  • 相关阅读:
    剑指offer_11:二进制中1的个数
    剑指offer_10:矩形覆盖
    spring mvc 访问静态资源
    spring context:component-scan ex
    spring aop配置未生效
    415 Unsupported Media Type
    spring mvc 接收List对象入参
    JIRA甘特图
    JIRA的工时
    JIRA导出工作日志到Excel
  • 原文地址:https://www.cnblogs.com/wabi87547568/p/5259769.html
Copyright © 2020-2023  润新知