crack the code intervie 4.8
来源:互联网 发布:中控考勤软件 编辑:程序博客网 时间:2024/04/28 22:03
You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree - it does not have to start at the root.
#include <list>
#include <iostream>using namespace std;
struct TreeNode
{
int value;
TreeNode * left;
TreeNode * right;
TreeNode(int v)
{
value = v;
left = NULL;
right = NULL;
}
TreeNode(int v, TreeNode * l, TreeNode * r)
{
value = v;
left = l;
right = r;
}
};
void mprint(list<int> path, int length);
void findSum(TreeNode * node, int sum_value, list<int> path, int length)
{
if (node == NULL)
return;
path.push_front(node->value);
int tmp = sum_value;
list<int>::iterator iter;
int i = 0;
for (iter = path.begin(); iter != path.end(); ++iter)
{
tmp -= *iter;
if (tmp == 0)
mprint(path, i);
i ++;
}
list<int> c1(path);
list<int> c2(path);
findSum(node->left, sum_value, c1, length + 1);
findSum(node->right, sum_value, c2, length + 1);
}
void mprint(list<int> path, int length)
{
list<int>::iterator iter;
for(iter = path.begin(); length >= 0; length --)
{
cout<<*iter<<" ";
iter ++;
}
cout<<endl;
}
int main()
{
TreeNode * node0 = new TreeNode(2);
TreeNode * node1 = new TreeNode(3, node0, NULL);
TreeNode * node2 = new TreeNode(-4, node1, NULL);
TreeNode * node3 = new TreeNode(3, node2, NULL);
TreeNode * node4 = new TreeNode(1, node3, NULL);
TreeNode * node5 = new TreeNode(2, node4, NULL);
list<int> path;
findSum(node5, 5, path, 0);
return 0;
}
0 0
- crack the code intervie 4.8
- Crack the code interview_Q1.1
- Crack the code interview_Q1.2
- Crack the code interview_Q1.3
- Crack the code interview_Q1.4
- crack the code interview1.1
- crack the code interview 1.2
- crack the code interview1.3
- crack the code interview 1.4
- crack the code interview 1.5
- crack the code interview 1.6
- crack the code interview 1.7
- crack the code interview 1.8
- crack the code interview 2.1
- crack the code interview 2.2
- crack the code interview 2.3
- crack the code interview 2.4
- crack the code interview 2.5
- bfs知识点
- Zedgraph用法
- 永远怀念Steve Jobs——时代的先驱者
- crack the code interview 4.7
- 驱动程序遇到问题记录
- crack the code intervie 4.8
- 嵌入式 c++对文件流操作--C++文件操作详解(ifstream、ofstream、fstream)
- 《转》一篇故事讲述了计算机网络里的基本概念:网关,DHCP,IP寻址,ARP欺骗,路由,DDOS等...
- AsyncHttpClient 帮助文档 (非常有用哦)
- if else
- 转帖 DM365 挂载NFS文件系统 【翻译】
- (CF)A. Vanya and Cards
- 黑马程序员-----------------进制间的转换
- 【Android 应用开发】Ubuntu 下 Android Studio 开发工具使用详解 (旧版本 | 仅作参考)