剑指Offer23 二叉树中和为sum的路径
1 /************************************************************************* 2 > File Name: 23_FindPath.cpp 3 > Author: Juntaran 4 > Mail: JuntaranMail@gmail.com 5 > Created Time: 2016年08月30日 星期二 20时49分34秒 6 ************************************************************************/ 7 8 #include <stdio.h> 9 #include <stdlib.h> 10 #include <bits/stdc++.h> 11 12 using namespace std; 13 14 // 二叉树结构体 15 struct TreeNode 16 { 17 int val; 18 TreeNode* left; 19 TreeNode* right; 20 }; 21 22 void FindPath(TreeNode* root, int sum); 23 void FindPath(TreeNode* root, int sum, vector<int> &path, int currentSum); 24 25 // 找到二叉树一条和为sum的路径 26 void FindPath(TreeNode* root, int sum) 27 { 28 if (root == NULL) 29 return; 30 31 vector<int> path; 32 int currentSum = 0; 33 FindPath(root, sum, path, currentSum); 34 } 35 36 void FindPath(TreeNode* root, int sum, vector<int> &path, int currentSum) 37 { 38 currentSum += root->val; 39 path.push_back(root->val); 40 41 // 如果走到叶子结点,和等于输入sum,输出 42 if (root->left==NULL && root->right==NULL && currentSum==sum) 43 { 44 printf("Find:\n"); 45 vector<int>::iterator iter = path.begin(); 46 for (; iter != path.end(); ++iter) 47 printf("%d\t", *iter); 48 printf("\n"); 49 } 50 51 // 如果不是叶子结点,继续遍历子结点 52 if (root->left) 53 FindPath(root->left, sum, path, currentSum); 54 if (root->right) 55 FindPath(root->right, sum, path, currentSum); 56 57 // 查找失败删除该结点 58 path.pop_back(); 59 } 60 61 TreeNode* createTree() 62 { 63 TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode)); 64 root->val = 10; 65 root->left = (TreeNode*)malloc(sizeof(TreeNode)); 66 root->left->val = 5; 67 root->right = (TreeNode*)malloc(sizeof(TreeNode)); 68 root->right->val = 12; 69 root->right->left = NULL; 70 root->right->right = NULL; 71 root->left->left = (TreeNode*)malloc(sizeof(TreeNode)); 72 root->left->left->val = 4; 73 root->left->left->left = NULL; 74 root->left->left->right = NULL; 75 root->left->right = (TreeNode*)malloc(sizeof(TreeNode)); 76 root->left->right->val = 7; 77 root->left->right->left = NULL; 78 root->left->right->right = NULL; 79 80 return root; 81 } 82 83 int main() 84 { 85 TreeNode* test = createTree(); 86 FindPath(test, 22); 87 }