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

来源:互联网 发布:淘宝2016好评返现新规 编辑:程序博客网 时间:2024/06/06 04:18

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

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

1、创建二叉树

2、前序遍历二叉树,如果根节点小于value加入vec

3、遍历左右孩子,value要减去当前根节点

4、如果某个节点左右孩子不符合条件,把该节点pop掉。

#include<iostream>#include<vector>using namespace std;typedef struct BinaryTreeNode // a node in the binary tree{int m_nValue; // value of nodeBinaryTreeNode *m_pLeft; // left child of nodeBinaryTreeNode *m_pRight; // right child of node}BinaryTree;//int sum = 0; //路径和void AddBinaryTreeNode( BinaryTree** root, int value ){if( (*root) == NULL ){(*root) = (BinaryTree *)malloc(sizeof(BinaryTree)); (*root)->m_nValue = value;(*root)->m_pLeft = NULL;(*root)->m_pRight = NULL;}else{if( (*root)->m_nValue > value ){AddBinaryTreeNode( &(*root)->m_pLeft, value );}else{AddBinaryTreeNode( &(*root)->m_pRight, value );}}}void GetPath( BinaryTree* root, int value ){static vector<int> vec;if(root == NULL)return;if( root->m_nValue > value )return;if( root->m_nValue <= value){vec.push_back(root->m_nValue);}if( value == root->m_nValue ){for( int i = 0; i < vec.size(); i++ ){cout << vec[i] << " ";}cout << endl;}GetPath( root->m_pLeft, value - root->m_nValue );//遍历左孩子GetPath( root->m_pRight, value - root->m_nValue );//遍历右孩子vec.pop_back();}int main(){int a[] = {10, 4, 5, 7, 16};BinaryTree* root = NULL;for(int i = 0; i < 5; ++i){AddBinaryTreeNode(&root, a[i]);}GetPath( root, 26 );return 0;}


原创粉丝点击