码迷,mamicode.com
首页 > 其他好文 > 详细

打印二叉树中和为某一值的路径

时间:2015-02-06 13:21:39      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>  
#include <tchar.h>
#include <vector>  
using namespace std;  
  
struct BinaryTreeNode  
{  
    int  m_nValue;  
    BinaryTreeNode *m_pLeft;  
    BinaryTreeNode *m_pRight;  
};  
  
void FindPath(BinaryTreeNode *pRoot, int nSum, vector<int>& path)  
{  
    if (pRoot == NULL || nSum == 0)  
    {  
        return;  
    }  
  
    if (pRoot->m_nValue == nSum && pRoot->m_pLeft == NULL && pRoot->m_pRight == NULL)  
    {  
      vector<int>::iterator iter = path.begin();  
      for (; iter!=path.end(); iter++)  
      {  
          cout << *iter << " ";  
      }  
      cout << pRoot->m_nValue << endl;  
      return;       
    }  
      
    path.push_back(pRoot->m_nValue);  
  
    if (pRoot->m_pLeft != NULL)  
    {  
        FindPath(pRoot->m_pLeft, nSum-pRoot->m_nValue, path);  
    }  
  
    if (pRoot->m_pRight != NULL)  
    {  
        FindPath(pRoot->m_pRight, nSum-pRoot->m_nValue, path);  
    }  
  
    path.pop_back();  
}  
  
//以先序的方式构建二叉树,输入-1表示结点为空  
void CreateBinaryTree(BinaryTreeNode *&pRoot)  
{  
    int nNodeValue = 0;  
    cin >> nNodeValue;      
    if (-1== nNodeValue)  
    {  
        pRoot = NULL;  
        return;   
    }  
    else  
    {  
        pRoot = new BinaryTreeNode();  
        pRoot->m_nValue = nNodeValue;  
        CreateBinaryTree(pRoot->m_pLeft);  
        CreateBinaryTree(pRoot->m_pRight);  
    }  
}  
  
void PrintInOrder(BinaryTreeNode *&pRoot)  
{  
    if (pRoot != NULL)  
    {  
        PrintInOrder(pRoot->m_pLeft);  
        cout << pRoot->m_nValue << " ";  
        PrintInOrder(pRoot->m_pRight);  
    }  
}  
  
int _tmain(int argc, _TCHAR* argv[])  
{  
    BinaryTreeNode *pRoot = NULL;  
    CreateBinaryTree(pRoot); 
cout <<"中序遍历为:"<<endl;
    PrintInOrder(pRoot);  
    cout << endl;  
    vector<int> path;  
    FindPath(pRoot, 22, path);  
    system("pause");  
    return 0;  
}  

打印二叉树中和为某一值的路径

标签:

原文地址:http://blog.csdn.net/u014082714/article/details/43562121

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!