记录几个问题:首先,这道题目要打印出该路径,那么该路径如何存储?
树的结构只能从根结点向下走,而不能向父节点寻找。因此寻找出一条路径的时候,存储这个路径必须借助其他的数据结构,没有比vector更适合的了。
如何遍历整个树?
这是很经典的问题,这道题目要从根结点->左子树->右子树。这是很明显的前序遍历,用递归(树)。
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 struct TreeNode { 5 int val; 6 struct TreeNode *left; 7 struct TreeNode *right; 8 }; 9 10 class Solution { 11 public: 12 vector<vector<int>> re;//数据成员 13 vector<vector<int> > FindPath(TreeNode* root1, int expectNumber1) { 14 if (root1 == NULL) 15 return re; 16 int count = 0; 17 vector<int> temp; 18 findit(root1,expectNumber1, temp, count); 19 return re; 20 } 21 //在递归函数中不能建立新的变量,可以建立静态变量 22 void findit(TreeNode* root, int expectNumber, vector<int> v2, int countsum) 23 { 24 countsum += root->val; 25 v2.push_back(root->val);//v2用来存储当前vector 26 bool isleaf = root->left == NULL&&root->right == NULL; 27 if (countsum == expectNumber&&isleaf) 28 { 29 //输出这个vector 30 for (int i = 0; i < v2.size(); i++) 31 { 32 cout << v2[i] << " "; 33 } 34 cout << endl; 35 re.push_back(v2); 36 } 37 if (root->left != NULL) 38 findit(root->left, expectNumber,v2, countsum); 39 if (root->right != NULL) 40 findit(root->right, expectNumber, v2, countsum); 41 //v2.pop_back();//如果使用静态变量需要恢复现场 42 } 43 44 }; 45 46 47 int main() 48 { 49 // 0 1 2 3 4 50 // {10,5,12,4,7},22 51 TreeNode TreeNode[5]; 52 TreeNode[0].val = 10; 53 TreeNode[0].left = &TreeNode[1]; 54 TreeNode[0].right = &TreeNode[2]; 55 56 TreeNode[1].val = 5; 57 TreeNode[1].left = &TreeNode[3]; 58 TreeNode[1].right = &TreeNode[4]; 59 60 TreeNode[2].val = 12; 61 TreeNode[2].left = NULL; 62 TreeNode[2].right = NULL; 63 64 TreeNode[3].val = 4; 65 TreeNode[3].left = NULL; 66 TreeNode[3].right = NULL; 67 68 TreeNode[4].val = 7; 69 TreeNode[4].left = NULL; 70 TreeNode[4].right = NULL; 71 72 Solution solu; 73 vector< vector<int> > res = solu.FindPath(&TreeNode[0], 22); 74 cout << "size = " << res.size()<<endl; 75 /* 76 for (int i = 0; i < res.size(); i++) 77 { 78 for (int j = 0; j < res[i].size(); j++) 79 { 80 cout << res[i][j] << " "; 81 } 82 cout << endl; 83 } 84 */ 85 return 0; 86 }
树的遍历,很重要的问题,一定要会!各种遍历方法都要熟悉。