zoukankan      html  css  js  c++  java
  • 18--二叉树中和为某一值的路径

    /*
    二叉树中和为某一值的路径
    题目:输入一个二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径,
    从树到根结点开始往下一直到叶结点所经过的结点形成一条路径,二叉树结点定义如下。

    strcut BinaryTreeNode
    {
    int m_Value;
    BinaryTreeNode *m_pleft;
    BinaryTreeNode *m_pright;
    };


    从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
    打印出和与输入整数相等的所有路径。
    例如 输入整数22和如下二元树
          10   
          /   
         5  12   
          /     
          4    7
    则打印出两条路径:10, 12和10, 5, 7。


    先序遍历树即可得到结果。

    到达一个节点之后计算当前节点和sum的和,如果为target,输出路径返回,如果大于target,则直接返回,如果小于,则将当前节点的值入栈,更新sum的值,继续遍历,遍历完成之后,也就是从当前节点返回的时候,将其从栈中弹出,更新sum

    */

    #include "stdafx.h"
    #include <iostream>
    #include <deque>
    using namespace std;
    
    struct TreeNode
    {
        int data;
        TreeNode* pLeftChild;
        TreeNode* pRightChild;
    };
    
    void CreateTree(TreeNode*& pRoot)
    {
        char buffer[10];  
        memset(buffer, 0, 10);  
        std::cin.getline(buffer, 9);  
        int a = atoi(buffer);  
        if(a == 0) pRoot = NULL;  
        else  
        {  
            pRoot = new TreeNode();  
            pRoot->data = a;  
            pRoot->pLeftChild = pRoot->pRightChild = NULL;  
            CreateTree(pRoot->pLeftChild);  
            CreateTree(pRoot->pRightChild);  
        }  
    }
    
    void PrintPath(TreeNode* pRoot, int sum, const int target)  
    {
        static deque<int> stack;  
    
        if(pRoot == NULL)    return;
        if(sum + pRoot->data == target)// 如果当前值加上路径和为目标值,则输出
        {
            for(int i=0; i<stack.size(); i++)
                cout<<stack[i]<<"->";
            cout<<pRoot->data<<endl;
            return;
        }
        else if(sum + pRoot->data > target)//如果大于目标值,则返回
        {
             return;
        }
        else// 如果小于,则入栈
        {
            stack.push_back(pRoot->data);
            sum += pRoot->data;
            PrintPath(pRoot->pLeftChild, sum, target);
            PrintPath(pRoot->pRightChild,sum,target);
            sum -= pRoot->data;
            stack.pop_back();
        }
    
    }
    
    int main()
    {
         TreeNode* pTree = NULL;  
        CreateTree(pTree); 
        PrintPath(pTree, 0, 22);  
    
    }
  • 相关阅读:
    基于.net 4.0框架的Cipher演示程序
    文件校验 加解密
    Base64加解密
    RSA加解密
    UBT框架加解密工具项目 UBT.Framework.Encryption
    AESTest
    message-digest algorithm 5
    Aforge.net
    Winform非UI线程更新UI界面的各种方法小结
    Hadoop-2.6.5安装
  • 原文地址:https://www.cnblogs.com/hgonlywj/p/4842568.html
Copyright © 2011-2022 走看看