OJ address
剑指Offer : 二叉树中和为某一值的路径
Description
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
Solution in C++
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
vector<vector<int> > vec;
vector<int> vecNode;
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if (!root) return vec;
vecNode.push_back(root->val);
if (root->val == expectNumber && !root->left && !root->right) {
vec.push_back(vecNode);
}
if (root->val < expectNumber) {
FindPath(root->left, expectNumber-root->val);
FindPath(root->right, expectNumber-root->val);
}
vecNode.pop_back();
return vec;
}
};
int main(int argc, char const *argv[])
{
TreeNode *t1 = new TreeNode(3);
TreeNode *t2 = new TreeNode(5);
TreeNode *t3 = new TreeNode(5);
TreeNode *t4 = new TreeNode(1);
TreeNode *t5 = new TreeNode(1);
TreeNode *t6 = new TreeNode(2);
t1->left = t2;
t1->right = t3;
t3->left = t4;
t4->left = t5;
t3->right = t6;
Solution solution;
vector<vector<int> > a = solution.FindPath(t1,8);
for (vector<vector<int> >::iterator it1 = a.begin(); it1 != a.end(); ++it1) {
for (vector<int>::iterator it2 = (*it1).begin(); it2 != (*it1).end(); ++it2) {
cout << *it2;
}
cout << endl;
}
return 0;
}
My Idea
通过DFS遍历每个二叉树根到叶子节点的路径,将路径保存到Vector动态数组中。如果动态数组刚好所有节点总和为给到的特定值,则将动态数组保存在二维动态数组中。主要是了解二维动态数组的声明以及使用,还有就是对二叉树结构的了解。
网友评论