1.在二元树中找出和为某一值的所有路径
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
二元树节点的数据结构定义为:
struct node // a node in the binary tree
{
int value; // value of node
node *Left; // left child of node
node *Right; // right child of node
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
二元树节点的数据结构定义为:
struct node // a node in the binary tree
{
int value; // value of node
node *Left; // left child of node
node *Right; // right child of node
};
首先这个问题需要的工具有栈,因为我们需要保存走过的路径,而且题目中要求是到叶节点的路径,也就是说我们需要采用某种遍历算法到达叶节点,然后再进行判断,那么采用哪种遍历算法呢?因为这里需要先访问根节点,所以我们需要前序遍历算法来访问二叉树.
void FindPath(node* root,int sum)
{
if(root==NULL)
return ;
stack<node*> sort_path;
int currentsum=0;
Find(root,sort_path,currentsum,sum);
}
void Find(node* root,stack<node*>& sort_path,currentsum,sum)
{
if(root==NULL)
return ;
currentsum+=root->value;
sort_path.push_back(root);
bool isLeaf=root->Left==NULL&&root->Right==NULL;
if(currentsum==sum&&isLeaf)
{
cout<<"a Paht has found: ";
stack<node*>::iterator pos=sort_path.begin();
for(;pos!=sort_path.end();pos++)
cout<<pos->value<<" ";
cout<<endl;
}
if(root->Left!=NULL)
Find(root->Left,sort_path,currentsum,sum);
if(root->Right!=NULL)
Find(root->Right,sort_path,currentsum,sum);
sort_path.pop();
currentsum-=root->value;//剑指上这句话没有,在P145大家可以看看
}
2.查找最小的k个元素
题目:输入n个整数,输出其中最小的k个。
例如输入1,2,3,4,5,6,7和8这8个数字,则最小的4个数字为1,2,3和4。
我想这个问题就不需要再多做解释,只需要建立小根堆,然后输出堆顶元素, 再重新建立新堆,重复k次搞定