zoukankan      html  css  js  c++  java
  • 在二叉树中找出和为某一值的所有路径

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


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

    算法: PrintPath(TreeNode* pRoot, int sum, const int target)  用来计算,sum为栈中的元素的和,target为目标值。

    到达一个节点之后计算当前节点和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);  
    
    }

    输入输出的结果如下:

    10
    5
    4
    #
    #
    7
    #
    #
    12
    #
    #


    10->5->7
    10->12

    前一半为输入,之后为输出。

  • 相关阅读:
    正则表达式的先行断言(lookahead)和后行断言(lookbehind)
    正则表达式里的捕获组
    JavaScript高级程序设计8.pdf
    JavaScript高级程序设计7.pdf
    JavaScript高级程序设计6.pdf
    JavaScript高级程序设计5.pdf
    JavaScript高级程序设计4.pdf
    产品思维|腾讯工作心得:原型该画到什么程度?
    提名推荐!15个2019年最佳CSS框架
    腾讯工作心得:原型该画到什么程度?
  • 原文地址:https://www.cnblogs.com/cyttina/p/2741811.html
Copyright © 2011-2022 走看看