在二元树中找出和为某一值的所有路径
来源:互联网 发布:淘宝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;}
- 在二元树中找出和为某一值的所有路径的个人代码
- 在二元树中找出和为某一值的所有路径(树)
- 在二元树中找出和为某一值的所有路径(树)
- 4.在二元树中找出和为某一值的所有路径(树)
- No4、在二元树中找出和为某一值的所有路径(树)
- 在二元树中找出和为某一值的所有路径(树)
- 在二元树中找出和为某一值的所有路径(树)
- 4.在二元树中找出和为某一值的所有路径(树)
- 4.在二元树中找出和为某一值的所有路径(树)
- 4.在二元树中找出和为某一值的所有路径(树)
- 在二元树中找出和为某一值的所有路径-递归算法
- 在二元树中找出和为某一值的所有路径
- 在二元树中找出和为某一值的所有路径
- 在二元树中找出和为某一值的所有路径
- 算法讨论(三)---在二元树中找出和为某一值的所有路径
- 在二元树中找出和为某一值的所有路径
- 算法题23 在二元树中找出和为某一值的所有路径
- 在二元树中找出和为某一值的所有路径
- 学习新技术的10个建议
- 解析LINUX core dump
- 3D视频的质量评价报告 (MSU出品)
- HDU 3530 Subsequence(单调队列)
- Linux下的画图软件
- 在二元树中找出和为某一值的所有路径
- Android平台下基于XMPP的IM研究
- <一>初探js特效魅力之选项卡05
- 九度online judge 1543 二叉树
- Git 的origin和master分析
- 给定无序自然数数组,求最大连续自然数个数,时间复杂度为O(n)
- 搭建XMPP协议,实现自主推送消息到手机
- 快速排序算法笔记
- 重叠的最长子串 (扩展KMP算法)(滚动哈希算法--Rabin-Karp算法)