/*
问题描述:给一棵二叉树,找出从根节点到叶子节点的所有路径。
来源:LintCode
作者:syt
问题描述:给一棵二叉树,找出从根节点到叶子节点的所有路径。
来源:LintCode
作者:syt
日期:2017-11-10
思路:迭代找出叶子节点并记录中间的寻找过程
*/
#include <iostream>
class TreeNode
{
public:
int val;
TreeNode *left, *right;
TreeNode(){}
TreeNode(int val, TreeNode *lptr = NULL, TreeNode *rptr = NULL) {
this->val = val;
this->left = lptr;
this->right = rptr;
}
};
#include "d_tree.h"
#include <vector>
#include <string>
using namespace std;
void findPaths(TreeNode *node, vector<string> &allPath, string path)
{
if (node->left == NULL && node->right == NULL)
{
allPath.push_back(path);
return;
}
//path = path + "->" + to_string(node->val);
if (node->left != NULL)
findPaths(node->left, allPath, path + "->" + to_string(node->left->val));
if (node->right != NULL)
findPaths(node->right, allPath, path + "->" + to_string(node->right->val));
}
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
vector<string> binaryTreePaths(TreeNode* root) {
// Write your code here
vector<string> result;
if (root != NULL)
{
string path = to_string(root->val);
findPaths(root, result, path);
}
return result;
}
TreeNode *buildTree(int n)
{
TreeNode *root, *b, *c, *d, *e, *f, *g, *h;
switch (n)
{
case 1:
e = new TreeNode(3);
d = new TreeNode(2);
c = new TreeNode(4);
b = new TreeNode(2, d, e);
root = new TreeNode(1, b, c);
break;
case 2:
h = new TreeNode(9);
g = new TreeNode(7);
f = new TreeNode(6);
e = new TreeNode(5);
d = new TreeNode(4, g, h);
c = new TreeNode(3, e, f);
b = new TreeNode(2, d, (TreeNode *)NULL);
root = new TreeNode(1, b, c);
break;
}
return root;
}
void main()
{
TreeNode *root = buildTree(1);
vector<string> result = binaryTreePaths(root);
for (int i = 0; i < result.size(); i++)
{
cout << result[i] << endl;
}
}