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


    题目:在二元树中找出和为某一值的所有路径

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

    // 在二元树中找出和为某一值的所有路径.cpp : Defines the entry point for the console application.
    //
    /*
    题目:在二元树中找出和为某一值的所有路径
    
    输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。
    例如输入整数22 和如下二元树          
    10        
    /        
    5  12     
    /     
    4 7
    则打印出两条路径:10, 12 和10, 5, 7。
    */
    
    #include "stdafx.h"
    #include <iostream>
    #include <stdlib.h>
    #include <vector>
    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
    };
    
    //BinaryTreeNode headNode = NULL;
    
    void addBSTreeNode(BinaryTreeNode *& pCurrent,int data)
    {
    	if (pCurrent == NULL)
    	{
    		BinaryTreeNode *BSTreeNode = new BinaryTreeNode();
    		BSTreeNode->m_pLeft = NULL;
    		BSTreeNode->m_pRight = NULL;
    		BSTreeNode->m_nValue = data;
    		pCurrent = BSTreeNode;
    	}else
    	{
    		if (pCurrent->m_nValue > data)
    		{
    			addBSTreeNode(pCurrent->m_pLeft,data);
    		}else
    		{
    			addBSTreeNode(pCurrent->m_pRight,data);
    		}
    	}
    }
    
    void findPath(BinaryTreeNode *pCurrent,int sum,vector<int> path,int curSum)
    {
    	if (!pCurrent)
    	{
    		return;
    	}
    	curSum += pCurrent->m_nValue;
    	path.push_back(pCurrent->m_nValue);
    	bool isLeaf = !(pCurrent->m_pLeft) && !(pCurrent->m_pRight);
    	if (curSum == sum && isLeaf)
    	{
    		vector<int>::iterator iter;
    		for (iter = path.begin();iter != path.end();iter++)
    		{
    			cout << *iter << "	";
    		}
    		cout << endl;
    	}
    	if (pCurrent->m_pLeft)
    	{
    		findPath(pCurrent->m_pLeft,sum,path,curSum);
    	}
    	if (pCurrent->m_pRight)
    	{
    		findPath(pCurrent->m_pRight,sum,path,curSum);
    	}
    	curSum -= pCurrent->m_nValue;
    	path.pop_back();
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
    	BinaryTreeNode *BSNode = NULL;
    	addBSTreeNode(BSNode,10);
    	addBSTreeNode(BSNode,5);
    	addBSTreeNode(BSNode,12);
    	addBSTreeNode(BSNode,4);
    	addBSTreeNode(BSNode,7);
    	vector<int> path;
    	int sum = 0;
    	findPath(BSNode,22,path,sum);
    		system("pause");
    	return 0;
    }
    
    
  • 相关阅读:
    学会了JsonPath,你的Python接口脚本才算完整
    史上最全的开发和设计等资源大全
    前后端分离事项
    二十一、spi驱动框架及驱动代码分析
    二十二、【devicetree】设备树的介绍
    uboot的作用
    InfluxDB大量写请求失败排查
    一些小知识点汇总
    InfluxDB配置优化
    windows server安装.net core环境
  • 原文地址:https://www.cnblogs.com/study-programmer/p/3408760.html
Copyright © 2020-2023  润新知